// 
// 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.Diagnostics.CodeAnalysis;
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 associationEntry.
    /// </summary>
    public sealed class AssociationEntryMapper : SqlDatabaseMapper<AssociationEntry>
    {
        internal AssociationEntryMapper(LogBase log)
            : base(log)
        {
        }

        private const string SelectSql =
            "SELECT " +
            "id, tallyChar, remote, refid, stratus, type, lastPoll, poll, reach, delay, [offset], jitter, hostId " +
            "FROM associationEntry";

        private const string InsertSql =
            "INSERT INTO associationEntry ( tallyChar, hostId, remote, refid, stratus, type, lastPoll, poll, reach, delay, [offset], jitter ) " +
            "VALUES ( @tallyChar, @hostId, @remote, @refid, @stratus, @type, @lastPoll, @poll, @reach, @delay, @offset, @jitter );{0};";

        private const string DeleteUniqueSql =
            "DELETE FROM associationEntry WHERE remote = @remote AND hostId = @hostId";

        private const string DeleteHostSql =
            "DELETE FROM associationEntry WHERE hostId = @hostId";

        protected override bool UseCache => false;

        protected override string TableName => "associationEntry";

        protected override string CreateSql => "CREATE TABLE associationEntry ( " +
                                               "    id {0} PRIMARY KEY, " +
                                               "    tallyChar CHAR(1) NOT NULL, " +
                                               "    remote VARCHAR(45) NOT NULL, " +
                                               "    refid VARCHAR(45) NOT NULL, " +
                                               "    stratus INT NOT NULL, " +
                                               "    type CHAR(1) NOT NULL, " +
                                               "    lastPoll INT NOT NULL, " +
                                               "    poll INT NOT NULL, " +
                                               "    reach INT NOT NULL, " +
                                               "    delay DOUBLE PRECISION NOT NULL, " +
                                               "    [offset] DOUBLE PRECISION NOT NULL, " +
                                               "    jitter DOUBLE PRECISION NOT NULL, " +
                                               "    hostId INT NOT NULL, " +
                                               "    UNIQUE KEY (hostId, remote), " +
                                               "    FOREIGN KEY (hostId) REFERENCES host(id) " +
                                               "){1};";

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        public void Delete(string ip, int hostId)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareSql(DeleteUniqueSql);
                    Command.Parameters.Add(CreateParameter("@remote", ip));
                    Command.Parameters.Add(CreateParameter("@hostId", hostId));
                    Command.Prepare();
                    Log.SqlExecute(Command.CommandText, Command.Parameters);
                    Command.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    Log.DeleteError(TableName, e);
                }
                finally
                {
                    Close();
                }
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        public void Delete(int hostId)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareSql(DeleteHostSql);
                    Command.Parameters.Add(CreateParameter("@hostId", hostId));
                    Command.Prepare();
                    Log.SqlExecute(Command.CommandText, Command.Parameters);
                    Command.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    Log.DeleteError(TableName, e);
                }
                finally
                {
                    Close();
                }
            }
        }

        /// <summary>
        /// Read all data from table in a sequential manner.
        /// </summary>
        /// <returns>The enumerator.</returns>
        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        public override IEnumerator<AssociationEntry> GetEnumerator()
        {
            lock (MapperLocker)
            {
                bool error = false;

                try
                {
                    Open();
                    Command.CommandText = PrepareSql(SelectSql);
                    Log.SqlExecute(Command.CommandText);
                    Reader = Command.ExecuteReader();
                }
                catch (Exception e)
                {
                    Log.ReadError(TableName, e);
                    error = true;
                }

                if (error)
                    yield break;

                while (Reader.Read())
                {
                    int id = Convert.ToInt32(Reader["id"]);
                    string tallyChar = Convert.ToString(Reader["tallyChar"]);
                    string remote = Convert.ToString(Reader["remote"]);
                    string refid = Convert.ToString(Reader["refid"]);
                    int stratus = Convert.ToInt32(Reader["stratus"]);
                    char type = Convert.ToChar(Reader["type"]);
                    int lastPoll = Convert.ToInt32(Reader["lastPoll"]);
                    int poll = Convert.ToInt32(Reader["poll"]);
                    int reach = Convert.ToInt32(Reader["reach"]);
                    double delay = Convert.ToDouble(Reader["delay"]);
                    double offset = Convert.ToDouble(Reader["offset"]);
                    double jitter = Convert.ToDouble(Reader["jitter"]);
                    int hostId = Convert.ToInt32(Reader["hostId"]);

                    if (tallyChar == string.Empty)
                        tallyChar = " ";

                    var entry = new AssociationEntry(
                        id, hostId, tallyChar[0], remote, refid, stratus, type,
                        lastPoll, poll, reach, delay, offset, jitter);

                    yield return entry;
                }

                Close();
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        protected override void Insert(AssociationEntry item)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareInsertSql(InsertSql);
                    Command.Parameters.Add(CreateParameter("@tallyChar", item.TallyChar));
                    Command.Parameters.Add(CreateParameter("@remote", item.Remote));
                    Command.Parameters.Add(CreateParameter("@refid", item.Refid));
                    Command.Parameters.Add(CreateParameter("@stratus", item.Stratus));
                    Command.Parameters.Add(CreateParameter("@type", item.PeerType));
                    Command.Parameters.Add(CreateParameter("@lastPoll", item.LastPoll));
                    Command.Parameters.Add(CreateParameter("@poll", item.Poll));
                    Command.Parameters.Add(CreateParameter("@reach", item.Reach));
                    Command.Parameters.Add(CreateParameter("@delay", item.Delay));
                    Command.Parameters.Add(CreateParameter("@offset", item.Offset));
                    Command.Parameters.Add(CreateParameter("@jitter", item.Jitter));
                    Command.Parameters.Add(CreateParameter("@hostId", item.HostId));
                    Command.Prepare();
                    Log.SqlExecute(Command.CommandText, Command.Parameters);
                    var idObject = Command.ExecuteScalar();
                    item.SetId(Convert.ToInt32(idObject));
                }
                catch (Exception e)
                {
                    Log.InsertError(TableName, e);
                }
                finally
                {
                    Close();
                }
            }
        }

        protected override void ReadContent()
        {
            throw new NotSupportedException(LogMessages.DatabaseCacheError);
        }

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