// 
// 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 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 peerActivity.
    /// </summary>
    public sealed class PeerActivityDatabaseMapper : SqlDatabaseMapper<PeerActivity>
    {
        internal PeerActivityDatabaseMapper(
            HostDatabaseMapper hostMapper,
            PeerDatabaseMapper peerMapper,
            LogBase log)
            : base(log)
        {
            this.hostMapper = hostMapper;
            this.peerMapper = peerMapper;
        }

        private const string SelectSql =
            "SELECT id, lastActive, zone, hide, hostId, peerId FROM peerActivity";

        private const string InsertSql =
            "INSERT INTO peerActivity( lastActive, zone, hide, hostId, peerId ) " +
            "VALUES( @lastActive, @zone, @hide, @hostId, @peerId );{0};";

        private const string UpdateSql =
            "UPDATE peerActivity SET lastActive = @lastActive, zone = @zone WHERE id = @id";

        private readonly HostDatabaseMapper hostMapper;
        private readonly PeerDatabaseMapper peerMapper;

        protected override bool UseCache => true;

        protected override string TableName => "peerActivity";

        protected override string CreateSql => "CREATE TABLE peerActivity ( " +
                                               "    id {0} PRIMARY KEY, " +
                                               "    lastActive TIMESTAMP NOT NULL, " +
                                               "    zone INT NOT NULL, " +
                                               "    hide BIT(1) NOT NULL, " +
                                               "    hostId INT NOT NULL, " +
                                               "    peerId INT NOT NULL, " +
                                               "    UNIQUE KEY (hostId, peerId), " +
                                               "    FOREIGN KEY (hostId) REFERENCES host(id), " +
                                               "    FOREIGN KEY (peerId) REFERENCES peer(id) " +
                                               "){1};";

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        protected override void Insert(PeerActivity item)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareInsertSql(InsertSql);
                    Command.Parameters.Add(CreateParameter("@lastActive", item.LastActive));
                    Command.Parameters.Add(CreateParameter("@zone", item.UtcOffset));
                    Command.Parameters.Add(CreateParameter("@hide", item.Hide));
                    Command.Parameters.Add(CreateParameter("@hostId", item.Host.Id));
                    Command.Parameters.Add(CreateParameter("@peerId", item.Peer.Id));
                    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();
                }
            }
        }

        [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"]);
                    var time = Convert.ToDateTime(Reader["lastActive"]);
                    int zone = Convert.ToInt32(Reader["zone"]);
                    bool hide = Convert.ToBoolean(Reader["hide"]);
                    int hostId = Convert.ToInt32(Reader["hostId"]);
                    var host = hostMapper[hostId];
                    int peerId = Convert.ToInt32(Reader["peerId"]);
                    var peer = peerMapper[peerId];
                    var item = new PeerActivity(id, peer, host, time, zone, hide);
                    AddItem(item);
                }
            }
            catch (Exception e)
            {
                Log.UpdateError(TableName, e);
            }
            finally
            {
                Close();
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        protected override void Update(PeerActivity item)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareSql(UpdateSql);
                    Command.Parameters.Add(CreateParameter("@lastActive", item.LastActive));
                    Command.Parameters.Add(CreateParameter("@zone", item.UtcOffset));
                    Command.Parameters.Add(CreateParameter("@id", item.Id));
                    Command.Prepare();
                    Log.SqlExecute(Command.CommandText, Command.Parameters);
                    Command.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    Log.UpdateError(TableName, e);
                }
                finally
                {
                    Close();
                }
            }
        }
    }
}