//
// TimeServerDatabaseMapper.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013-2016 Carsten Sonne Larsen
//
// 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.Net;
using Ntp.Analyzer.Data.Import;
using Ntp.Analyzer.Localize;
using Ntp.Log;
using Ntp.Analyzer.Objects;

namespace Ntp.Analyzer.Data.Sql
{
    /// <summary>
    /// ORM mapper for table timeServer.
    /// </summary>
    public sealed class TimeServerDatabaseMapper : SqlDatabaseMapper<TimeServer>
    {
        internal TimeServerDatabaseMapper(LogBase log)
            : base(log)
        {
        }

        private const string SelectSql =
            "SELECT id, stratum, countryCode, hostName, ip, ip6, " +
            "useDns+0 as dns, poolMember+0 as pool, location, displayLocation, organization, " +
            "coordinates, synchronization, serviceArea, accessPolicy, " +
            "accessDetails, notification+0 as noti, autoKeyUrl, symmetricKeyType, " +
            "symmetricKeyURL, serverContact, providerPage, providerUrl, " +
            "updated " +
            "FROM timeServer;";

        private const string InsertSql =
            "INSERT INTO timeServer(id, stratum, countryCode, hostName, ip, ip6, " +
            "useDns, poolMember, location, displayLocation, organization, " +
            "coordinates, synchronization, serviceArea, accessPolicy, " +
            "accessDetails, notification, autoKeyUrl, symmetricKeyType, " +
            "symmetricKeyURL, serverContact, providerPage, providerUrl, " +
            "updated) " +
            "VALUES (@id, @stratum, @countryCode, @hostName, @ip, @ip6, " +
            "@useDns, @poolMember, @location, @displayLocation, @organization, " +
            "@coordinates, @synchronization, @serviceArea, @accessPolicy, " +
            "@accessDetails, @notification, @autoKeyUrl, @symmetricKeyType, " +
            "@symmetricKeyURL, @serverContact, @providerPage, @providerUrl, " +
            "@updated);";

        protected override bool UseCache
        {
            get { return true; }
        }

        protected override string TableName
        {
            get { return "timeServer"; }
        }

        protected override string CreateSql
        {
            get
            {
                return
                    "CREATE TABLE timeServer ( " +
                    "    id INT NOT NULL PRIMARY KEY, " +
                    "    stratum INT NOT NULL, " +
                    "    countryCode CHAR(7) NOT NULL, " +
                    "    hostName VARCHAR(50) NOT NULL, " +
                    "    ip VARCHAR(15) NULL, " +
                    "    ip6 VARCHAR(30) NULL, " +
                    "    useDns BIT(1) NULL, " +
                    "    poolMember BIT(1) NULL, " +
                    "    location VARCHAR(100) NULL, " +
                    "    displayLocation VARCHAR(60) NOT NULL, " +
                    "    organization VARCHAR(50) NULL, " +
                    "    coordinates VARCHAR(50) NULL, " +
                    "    synchronization VARCHAR(255) NULL, " +
                    "    serviceArea VARCHAR(100) NULL, " +
                    "    accessPolicy VARCHAR(255) NULL, " +
                    "    accessDetails VARCHAR(512) NULL, " +
                    "    notification BIT(1) NULL, " +
                    "    autoKeyUrl VARCHAR(255) NULL, " +
                    "    symmetricKeyType VARCHAR(100) NULL, " +
                    "    symmetricKeyURL VARCHAR(100) NULL, " +
                    "    serverContact VARCHAR(255) NULL, " +
                    "    updated TIMESTAMP NOT NULL, " +
                    "    providerPage VARCHAR(100) NULL, " +
                    "    providerUrl VARCHAR(255) NULL " +
                    "){1};";
            }
        }

        protected override void ReadContent()
        {
            try
            {
                Open();
                Command.CommandText = PrepareSql(SelectSql);
                Reader = Command.ExecuteReader();

                while (Reader.Read())
                {
                    int id = Convert.ToInt32(Reader["id"]);
                    int stratum = Convert.ToInt32(Reader["stratum"]);
                    string countryCode = Reader["countryCode"].ToString();
                    string hostName = Reader["hostName"].ToString();
                    string ip4 = (Reader["ip"] != DBNull.Value) ? Reader["ip"].ToString() : null;
                    string ip6 = (Reader["ip6"] != DBNull.Value) ? Reader["ip6"].ToString() : null;
                    bool? useDns = (Reader["dns"] != DBNull.Value) ? Convert.ToBoolean(Reader["dns"]) : (bool?) null;
                    bool? poolMember = Reader["pool"] != DBNull.Value ? Convert.ToBoolean(Reader["pool"]) : (bool?) null;
                    string location = Reader["location"].ToString();
                    string displayLocation = Reader["displayLocation"].ToString();
                    string organization = (Reader["organization"] != DBNull.Value)
                        ? Reader["organization"].ToString()
                        : null;
                    string coordinates = (Reader["coordinates"] != DBNull.Value)
                        ? Reader["organization"].ToString()
                        : null;
                    string synchronization = Reader["synchronization"].ToString();
                    string serviceArea = Reader["serviceArea"].ToString();
                    string accessPolicy = Reader["accessPolicy"].ToString();
                    string accessDetails = (Reader["accessDetails"] != DBNull.Value)
                        ? Reader["accessDetails"].ToString()
                        : null;
                    bool? notification = (Reader["noti"] != DBNull.Value)
                        ? Convert.ToBoolean(Reader["noti"])
                        : (bool?) null;
                    string autoKeyUrl = (Reader["autoKeyUrl"] != DBNull.Value) ? Reader["autoKeyUrl"].ToString() : null;
                    string symmetricKeyType = (Reader["symmetricKeyType"] != DBNull.Value)
                        ? Reader["symmetricKeyType"].ToString()
                        : null;
                    string symmetricKeyUrl = (Reader["symmetricKeyURL"] != DBNull.Value)
                        ? Reader["symmetricKeyURL"].ToString()
                        : null;
                    string serverContact = (Reader["serverContact"] != DBNull.Value)
                        ? Reader["serverContact"].ToString()
                        : null;
                    string providerPage = (Reader["providerPage"] != DBNull.Value)
                        ? Reader["providerPage"].ToString()
                        : null;
                    string providerUrl = (Reader["providerUrl"] != DBNull.Value)
                        ? Reader["providerUrl"].ToString()
                        : null;
                    DateTime updated = Convert.ToDateTime(Reader["updated"]);

                    IPAddress address = null;
                    if (ip4 != null)
                        IPAddress.TryParse(ip4, out address);

                    var server = new TimeServer(
                        id, stratum, countryCode, hostName, address, ip6, useDns, poolMember, location,
                        displayLocation, organization, coordinates, synchronization, serviceArea, accessDetails,
                        accessPolicy, notification, autoKeyUrl, symmetricKeyType, symmetricKeyUrl, serverContact,
                        providerPage, providerUrl, updated);

                    AddItem(server);
                }
            }
            catch (Exception e)
            {
                Log.WriteLine(String.Format(
                    LogMessage.DatabaseTableError, LogMessage.DatabaseRead, TableName, e.Message),
                    Severity.Error);
                Log.WriteLine(e, Severity.Trace);
            }
            finally
            {
                Close();
            }
        }

        protected override void Insert(TimeServer item)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareInsertSql(InsertSql);
                    Command.Parameters.Add(CreateParameter("@id", item.Id));
                    Command.Parameters.Add(CreateParameter("@stratum", item.Stratum));
                    Command.Parameters.Add(CreateParameter("@countryCode", item.Country));
                    Command.Parameters.Add(CreateParameter("@hostName", item.Name));
                    Command.Parameters.Add(CreateParameter("@ip",
                        (item.Address != null) ? (object) item.Address.ToString() : DBNull.Value));
                    Command.Parameters.Add(CreateParameter("@ip6",
                        (object) item.V6Address ?? DBNull.Value));
                    Command.Parameters.Add(CreateParameter("@useDns", item.ShouldUseDns));
                    Command.Parameters.Add(CreateParameter("@poolMember", item.IsPoolMember));
                    Command.Parameters.Add(CreateParameter("@location", item.Location));
                    Command.Parameters.Add(CreateParameter("@displayLocation", item.DisplayLocation));
                    Command.Parameters.Add(CreateParameter("@organization", item.Organization));
                    Command.Parameters.Add(CreateParameter("@coordinates", item.Geo));
                    Command.Parameters.Add(CreateParameter("@synchronization", item.Server));
                    Command.Parameters.Add(CreateParameter("@serviceArea", item.ServiceArea));
                    Command.Parameters.Add(CreateParameter("@accessPolicy", item.AccessPolicy));
                    Command.Parameters.Add(CreateParameter("@accessDetails", item.AccessDetails));
                    Command.Parameters.Add(CreateParameter("@notification", item.ShouldNotify));
                    Command.Parameters.Add(CreateParameter("@autoKeyUrl", item.AutoKey));
                    Command.Parameters.Add(CreateParameter("@symmetricKeyType", item.SymKey));
                    Command.Parameters.Add(CreateParameter("@symmetricKeyURL", item.SymUrl));
                    Command.Parameters.Add(CreateParameter("@serverContact", item.Contact));
                    Command.Parameters.Add(CreateParameter("@providerPage", item.ProviderPage));
                    Command.Parameters.Add(CreateParameter("@providerUrl", item.ProviderUrl));
                    Command.Parameters.Add(CreateParameter("@updated", item.Updated));
                    Command.Prepare();
                    Command.ExecuteNonQuery();
                    item.SetId(item.Id);
                }
                catch (Exception e)
                {
                    Log.WriteLine(String.Format(
                        LogMessage.DatabaseTableError, LogMessage.DatabaseInsert, TableName, e.Message),
                        Severity.Error);
                    Log.WriteLine(e, Severity.Trace);
                }
                finally
                {
                    Close();
                }
            }
        }

        protected override void Update(TimeServer item)
        {
            throw new NotSupportedException(String.Format(LogMessage.DatabaseNoUpdate, TableName));
        }

        /// <summary>
        /// Fetch time server from external source.
        /// </summary>
        /// <returns>The external.</returns>
        /// <param name="id">The time server identifier used on support.ntp.org.</param>
        protected override TimeServer FetchExternal(int id)
        {
            var loader = new TimeServerLoader(Log);
            var importer = new TimeServerImporter(Log);
            TimeServer server;

            try
            {
                string table = loader.ImportServer(id);
                if (table == null)
                {
                    return null;
                }

                server = importer.ParseTable(table, id);
                Insert(server);
                AddItem(server);
            }
            catch (Exception e)
            {
                throw new ApplicationException("Failed to fetch time server data.", e);
            }

            return server;
        }
    }
}