// 
// 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 hostIoReading.
    /// </summary>
    public sealed class HostIoReadingDatabaseMapper : FilteredSqlDatabaseMapper<HostIoReading>
    {
        internal HostIoReadingDatabaseMapper(HostDatabaseMapper hostMapper, LogBase log)
            : base(log)
        {
            this.hostMapper = hostMapper;
        }

        private const string SelectSql =
            "SELECT " +
            "id, time, zone, hostId, timeSinceReset, " +
            "receiveBuffers, freeReceiveBuffers, usedReceiveBuffers, lowWaterRefills, " +
            "droppedPackets, ignoredPackets, receivedPackets, " +
            "packetsSent, packetsNotSent, interruptsHandled, receivedByInt " +
            "FROM hostIoReading";

        private const string InsertSql =
            "INSERT INTO hostIoReading ( " +
            "time, zone, hostId, timeSinceReset, " +
            "receiveBuffers, freeReceiveBuffers, usedReceiveBuffers, lowWaterRefills, " +
            "droppedPackets, ignoredPackets, receivedPackets, " +
            "packetsSent, packetsNotSent, interruptsHandled, receivedByInt ) " +
            "VALUES ( " +
            "@time, @zone, @hostId, @timeSinceReset, " +
            "@receiveBuffers, @freeReceiveBuffers, @usedReceiveBuffers, @lowWaterRefills, " +
            "@droppedPackets, @ignoredPackets, @receivedPackets, " +
            "@packetsSent, @packetsNotSent, @interruptsHandled, @receivedByInt );{0};";

        private readonly HostDatabaseMapper hostMapper;

        protected override bool UseCache => false;

        protected override string TableName => "hostIoReading";

        protected override string CreateSql => "CREATE TABLE hostIoReading ( " +
                                               "    id {0} PRIMARY KEY, " +
                                               "    time TIMESTAMP NOT NULL, " +
                                               "    zone INT NOT NULL, " +
                                               "    hostId INT NOT NULL, " +
                                               "    timeSinceReset INT NOT NULL, " +
                                               "    receiveBuffers INT NOT NULL, " +
                                               "    freeReceiveBuffers INT NOT NULL, " +
                                               "    usedReceiveBuffers INT NOT NULL, " +
                                               "    lowWaterRefills INT NOT NULL, " +
                                               "    droppedPackets BIGINT NOT NULL, " +
                                               "    ignoredPackets BIGINT NOT NULL, " +
                                               "    receivedPackets BIGINT NOT NULL, " +
                                               "    packetsSent BIGINT NOT NULL, " +
                                               "    packetsNotSent BIGINT NOT NULL, " +
                                               "    interruptsHandled INT NOT NULL, " +
                                               "    receivedByInt INT NOT NULL, " +
                                               "    FOREIGN KEY (hostId) REFERENCES host(id) " +
                                               "){1};";

        /// <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<HostIoReading> 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"]);
                    var time = Convert.ToDateTime(Reader["time"]);
                    int zone = Convert.ToInt32(Reader["zone"]);
                    int hostId = Convert.ToInt32(Reader["hostId"]);
                    var host = hostMapper[hostId];
                    int timeSinceReset = Convert.ToInt32(Reader["timeSinceReset"]);
                    int receiveBuffers = Convert.ToInt32(Reader["receiveBuffers"]);
                    int freeReceiveBuffers = Convert.ToInt32(Reader["freeReceiveBuffers"]);
                    int usedReceiveBuffers = Convert.ToInt32(Reader["usedReceiveBuffers"]);
                    int lowWaterRefills = Convert.ToInt32(Reader["lowWaterRefills"]);
                    long droppedPackets = Convert.ToInt64(Reader["droppedPackets"]);
                    long ignoredPackets = Convert.ToInt64(Reader["ignoredPackets"]);
                    long receivedPackets = Convert.ToInt64(Reader["receivedPackets"]);
                    long packetsSent = Convert.ToInt64(Reader["packetsSent"]);
                    long packetsNotSent = Convert.ToInt64(Reader["packetsNotSent"]);
                    int interruptsHandled = Convert.ToInt32(Reader["interruptsHandled"]);
                    int receivedByInt = Convert.ToInt32(Reader["receivedByInt"]);

                    var reading = new HostIoReading(
                        id, time, zone, host, timeSinceReset,
                        receiveBuffers, freeReceiveBuffers, usedReceiveBuffers, lowWaterRefills,
                        droppedPackets, ignoredPackets, receivedPackets,
                        packetsSent, packetsNotSent,
                        interruptsHandled, receivedByInt);

                    yield return reading;
                }

                Close();
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        protected override void Insert(HostIoReading item)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareInsertSql(InsertSql);
                    Command.Parameters.Add(CreateParameter("@time", item.Time));
                    Command.Parameters.Add(CreateParameter("@zone", item.UtcOffset));
                    Command.Parameters.Add(CreateParameter("@hostId", item.Host.Id));
                    Command.Parameters.Add(CreateParameter("@timeSinceReset", item.TimeSinceReset));
                    Command.Parameters.Add(CreateParameter("@receiveBuffers", item.ReceiveBuffers));
                    Command.Parameters.Add(CreateParameter("@freeReceiveBuffers", item.FreeReceiveBuffers));
                    Command.Parameters.Add(CreateParameter("@usedReceiveBuffers", item.UsedReceiveBuffers));
                    Command.Parameters.Add(CreateParameter("@lowWaterRefills", item.LowWaterRefills));
                    Command.Parameters.Add(CreateParameter("@droppedPackets", item.DroppedPackets));
                    Command.Parameters.Add(CreateParameter("@ignoredPackets", item.IgnoredPackets));
                    Command.Parameters.Add(CreateParameter("@receivedPackets", item.ReceivedPackets));
                    Command.Parameters.Add(CreateParameter("@packetsSent", item.PacketsSent));
                    Command.Parameters.Add(CreateParameter("@packetsNotSent", item.PacketsNotSent));
                    Command.Parameters.Add(CreateParameter("@interruptsHandled", item.InterruptsHandled));
                    Command.Parameters.Add(CreateParameter("@receivedByInt", item.ReceivedByInt));
                    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(HostIoReading item)
        {
            throw new NotSupportedException(string.Format(LogMessages.DatabaseNoUpdate, TableName));
        }
    }
}