// 
// 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.Diagnostics.CodeAnalysis;
using System.Net;
using Ntp.Analyzer.Data.Import;
using Ntp.Analyzer.Data.Log;
using Ntp.Analyzer.Objects;
using Ntp.Common.Log;
using Ntp.Data.Log;

namespace Ntp.Analyzer.Data.Sql
{
    /// <summary>
    /// OR/M 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 => true;

        protected override string TableName => "timeServer";

        protected override string CreateSql => "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};";

        /// <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 adapter = TimeServerWebAdapter.Create(Log);

            if (adapter == null)
                return null;

            TimeServer server;

            try
            {
                server = adapter.Import(id);
                Insert(server);
                AddItem(server);
            }
            catch (Exception e)
            {
                Log.TimeServerFetchError(e);
                return null;
            }

            return server;
        }

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        protected override void Insert(TimeServer item)
        {
            string countryCode = item.Country?.PadRight(7).Substring(0, 7).TrimEnd();
            string hostName = item.Name?.PadRight(50).Substring(0, 50).TrimEnd();
            string ip = item.Address?.ToString().PadRight(15).Substring(0, 15).TrimEnd();
            string ip6 = item.V6Address?.PadRight(30).Substring(0, 30).TrimEnd();
            string location = item.Location?.PadRight(100).Substring(0, 100).TrimEnd();
            string displayLocation = item.DisplayLocation?.PadRight(60).Substring(0, 60).TrimEnd();
            string organization = item.Organization?.PadRight(50).Substring(0, 50).TrimEnd();
            string coordinates = item.Geo?.PadRight(50).Substring(0, 50).TrimEnd();
            string synchronization = item.Server?.PadRight(255).Substring(0, 255).TrimEnd();
            string serviceArea = item.ServiceArea?.PadRight(100).Substring(0, 100).TrimEnd();
            string accessPolicy = item.AccessPolicy?.PadRight(255).Substring(0, 255).TrimEnd();
            string accessDetails = item.AccessDetails?.PadRight(512).Substring(0, 512).TrimEnd();
            string autoKeyUrl = item.AutoKey?.PadRight(255).Substring(0, 255).TrimEnd();
            string symmetricKeyType = item.SymKey?.PadRight(100).Substring(0, 100).TrimEnd();
            string symmetricKeyUrl = item.SymUrl?.PadRight(100).Substring(0, 100).TrimEnd();
            string serverContact = item.Contact?.PadRight(255).Substring(0, 255).TrimEnd();
            string providerPage = item.ProviderPage?.PadRight(100).Substring(0, 100).TrimEnd();
            string providerUrl = item.ProviderUrl?.PadRight(255).Substring(0, 255).TrimEnd();

            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", countryCode));
                    Command.Parameters.Add(CreateParameter("@hostName", hostName));
                    Command.Parameters.Add(CreateParameter("@ip", ip));
                    Command.Parameters.Add(CreateParameter("@ip6", ip6));
                    Command.Parameters.Add(CreateParameter("@useDns", item.ShouldUseDns));
                    Command.Parameters.Add(CreateParameter("@poolMember", item.IsPoolMember));
                    Command.Parameters.Add(CreateParameter("@location", location));
                    Command.Parameters.Add(CreateParameter("@displayLocation", displayLocation));
                    Command.Parameters.Add(CreateParameter("@organization", organization));
                    Command.Parameters.Add(CreateParameter("@coordinates", coordinates));
                    Command.Parameters.Add(CreateParameter("@synchronization", synchronization));
                    Command.Parameters.Add(CreateParameter("@serviceArea", serviceArea));
                    Command.Parameters.Add(CreateParameter("@accessPolicy", accessPolicy));
                    Command.Parameters.Add(CreateParameter("@accessDetails", accessDetails));
                    Command.Parameters.Add(CreateParameter("@notification", item.ShouldNotify));
                    Command.Parameters.Add(CreateParameter("@autoKeyUrl", autoKeyUrl));
                    Command.Parameters.Add(CreateParameter("@symmetricKeyType", symmetricKeyType));
                    Command.Parameters.Add(CreateParameter("@symmetricKeyURL", symmetricKeyUrl));
                    Command.Parameters.Add(CreateParameter("@serverContact", serverContact));
                    Command.Parameters.Add(CreateParameter("@providerPage", providerPage));
                    Command.Parameters.Add(CreateParameter("@providerUrl", providerUrl));
                    Command.Parameters.Add(CreateParameter("@updated", item.Updated));
                    Command.Prepare();
                    Log.SqlExecute(Command.CommandText, Command.Parameters);
                    Command.ExecuteNonQuery();
                    item.SetId(item.Id);
                }
                catch (Exception e)
                {
                    Log.InsertError(TableName, e);
                }
                finally
                {
                    Close();
                }
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        protected override void ReadContent()
        {
            try
            {
                Open();
                Command.CommandText = PrepareSql(SelectSql);
                Log.SqlExecute(Command.CommandText);
                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 CalgaryTimeServer(
                        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.ReadError(TableName, e);
            }
            finally
            {
                Close();
            }
        }

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