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

namespace Ntp.Analyzer.Data.Static
{
    /// <summary>
    /// ORM mapper for table timeServer.
    /// </summary>
    public sealed class TimeServerDatabaseMapper : DatabaseMapper<TimeServer>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Ntp.Analyzer.Data.Mapper.TimeServerDatabaseMapper" /> class.
        /// </summary>
        internal TimeServerDatabaseMapper (LogBase log)
            : base(log)
        {
        }

        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 DEFAULT 'Unknown', " +
                    "    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 DEFAULT CURRENT_TIMESTAMP(), " +
                    "    providerPage VARCHAR(100) NULL, " +
                    "    providerUrl VARCHAR(255) NULL " +
                    ") ENGINE=INNODB;";
            }
        }

        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 void Insert (TimeServer item)
        {
            lock (Locker) {
                try {
                    Open ();

                    Command.CommandText = insertSql;
                    Command.Prepare ();

                    Command.Parameters.AddWithValue ("?id", item.Id);
                    Command.Parameters.AddWithValue ("?stratum", item.Stratum);
                    Command.Parameters.AddWithValue ("?countryCode", item.Country);
                    Command.Parameters.AddWithValue ("?hostName", item.Name);
                    Command.Parameters.AddWithValue ("?ip", (item.Address != null) ? (object)item.Address.ToString () : DBNull.Value);
                    Command.Parameters.AddWithValue ("?ip6", (object)item.V6Address ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?useDns", (object)item.ShouldUseDns ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?poolMember", (object)item.IsPoolMember ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?location", (object)item.Location ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?displayLocation", item.DisplayLocation);
                    Command.Parameters.AddWithValue ("?organization", (object)item.Organization ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?coordinates", (object)item.Geo ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?synchronization", (object)item.Server ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?serviceArea", (object)item.ServiceArea ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?accessPolicy", (object)item.AccessPolicy ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?accessDetails", (object)item.AccessDetails ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?notification", (object)item.ShouldNotify ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?autoKeyUrl", (object)item.AutoKey ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?symmetricKeyType", (object)item.SymKey ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?symmetricKeyURL", (object)item.SymUrl ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?serverContact", (object)item.Contact ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?providerPage", (object)item.ProviderPage ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?providerUrl", (object)item.ProviderUrl ?? DBNull.Value);
                    Command.Parameters.AddWithValue ("?updated", item.Updated);

                    Command.ExecuteNonQuery ();
                    item.SetId (item.Id);
                } finally {
                    Close ();
                }
            }
        }

        protected override void Update (TimeServer item)
        {
            throw new NotImplementedException ("TimeServerDatabaseMapper does not implement an update of data");
        }

        /// <summary>
        /// Read all data from table in a sequential manner.
        /// </summary>
        /// <returns>The enumerator.</returns>
        public override IEnumerator<TimeServer> GetEnumerator ()
        {
            lock (Locker) {

                if (HasContent) {
                    foreach (TimeServer host in Content)
                        yield return host;

                    yield break;
                }

                try {
                    Open ();
                    Command.CommandText = 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);

                        TimeServer 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);

                        yield return server;
                    }
                } finally {
                    Close ();
                }
            }
        }

        /// <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)
        {
            TimeServerLoader loader = new TimeServerLoader (Log);
            TimeServerImporter 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;
        }
    }
}
