// 
// Copyright (c) 2013-2016 Carsten Sonne Larsen <cs@innolan.dk>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;
using Ntp.Analyzer.Objects;
using Ntp.Common.Log;

namespace Ntp.Analyzer.Data.Import
{
    internal sealed class TimeServerImporter
    {
        internal TimeServerImporter(LogBase log)
        {
            this.log = log;
        }

        private readonly LogBase log;

        internal TimeServer ParseTable(string table, int orgId)
        {
            if (table == null)
            {
                log.WriteLine("Not parsing empty HTML.", Severity.Debug);
                return null;
            }

            try
            {
                var doc = new XmlDocument();
                doc.LoadXml(table);

                XmlNodeList rows = doc.ChildNodes[0].ChildNodes;

                bool firstRow = true;

                var entries = new Dictionary<string, string>();

                foreach (XmlNode node in rows)
                {
                    if (firstRow)
                    {
                        firstRow = false;
                        continue;
                    }

                    entries.Add(
                        node.ChildNodes[0].InnerText.Trim(),
                        node.ChildNodes[1].InnerText.Trim()
                        );
                }

                if (!entries.ContainsKey("IPv6 Address"))
                {
                    entries.Add("IPv6 Address", string.Empty);
                }
                if (!entries.ContainsKey("HostOrganization"))
                {
                    entries.Add("HostOrganization", string.Empty);
                }
                if (!entries.ContainsKey("AutoKeyURL"))
                {
                    entries.Add("AutoKeyURL", string.Empty);
                }
                if (!entries.ContainsKey("SymmetricKeyType"))
                {
                    entries.Add("SymmetricKeyType", string.Empty);
                }
                if (!entries.ContainsKey("SymmetricKeyURL"))
                {
                    entries.Add("SymmetricKeyURL", string.Empty);
                }

                string stratusStr = entries["ServerStratum"];
                string country = entries["CountryCode"];
                string name = entries["Hostname"];
                string ip = entries["IP Address"];
                string ip6 = entries["IPv6 Address"];
                string useDnsStr = entries["UseDNS"];
                string poolMemberStr = entries["PoolMember"];
                string location = entries["ServerLocation"];
                string display = entries["ServerLocation"];
                string org = entries["HostOrganization"];
                string geo = entries["GeographicCoordinates"];
                string server = entries["ServerSynchronization"];
                string serviceArea = entries["ServiceArea"];
                string accessPolicy = entries["AccessPolicy"];
                string accessDetails = entries["AccessDetails"];
                string notificationStr = entries["NotificationMessage"];
                string autoKey = entries["AutoKeyURL"];
                string symKey = entries["SymmetricKeyType"];
                string symUrl = entries["SymmetricKeyURL"];
                string contact = entries["ServerContact"];

                int stratus;

                if (stratusStr == "StratumOne")
                {
                    stratus = 1;
                }
                else if (stratusStr == "StratumTwo")
                {
                    stratus = 2;
                }
                else
                {
                    stratus = 19;
                }

                IPAddress address;
                IPAddress.TryParse(ip, out address);

                bool? useDns = GetBool(useDnsStr);
                bool? poolMember = GetBool(poolMemberStr);
                bool? notification = GetBool(notificationStr);

                return new CalgaryTimeServer(
                    orgId, stratus, country, name, address, ip6, useDns, poolMember, location,
                    display, org, geo, server, serviceArea, accessDetails, accessPolicy,
                    notification, autoKey, symKey, symUrl, contact, null, null, DateTime.Now);
            }
            catch (Exception e)
            {
                log.WriteLine("Could not parse TimeServer HTML.", Severity.Error);
                log.WriteLine(e);
                return null;
            }
        }

        private bool? GetBool(string boolString)
        {
            string test = boolString.Trim().ToLower();

            if (test == "yes")
                return true;
            if (test == "no")
                return false;
            if (test == string.Empty)
                return null;

            throw new ApplicationException("Unknown boolean type.");
        }
    }
}