// 
// 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 peer.
    /// </summary>
    public sealed class PeerDatabaseMapper : SqlDatabaseMapper<Peer>
    {
        internal PeerDatabaseMapper(TimeServerDatabaseMapper timeServerMapper, LogBase log)
            : base(log)
        {
            this.timeServerMapper = timeServerMapper;
        }

        private const string SelectSql =
            "SELECT id, name, ip, orgId FROM peer;";

        private const string InsertSql =
            "INSERT INTO peer( name, ip, orgId ) VALUES( @name, @ip, @orgId );{0};";

        private const string UpdateSql =
            "UPDATE peer SET name = @name, ip = @ip, orgId = @orgId WHERE id = @id";

        private readonly TimeServerDatabaseMapper timeServerMapper;

        protected override bool UseCache => true;

        protected override string TableName => "peer";

        protected override string CreateSql => "CREATE TABLE peer ( " +
                                               "    id {0} PRIMARY KEY, " +
                                               "    name VARCHAR(255) NOT NULL, " +
                                               "    ip VARCHAR(45) NOT NULL, " +
                                               "    orgId INT " +
                                               "){1};";

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        protected override void Insert(Peer item)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareInsertSql(InsertSql);
                    Command.Parameters.Add(CreateParameter("@name", item.Name));
                    Command.Parameters.Add(CreateParameter("@ip", item.Ip));
                    Command.Parameters.Add(CreateParameter("@orgId", item.OrgId));
                    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"]);
                    string name = Reader["name"].ToString();
                    string ip = Reader["ip"].ToString();
                    var orgId = Reader["orgId"] != DBNull.Value
                        ? Convert.ToInt32(Reader["orgId"])
                        : (int?) null;

                    var server = orgId.HasValue
                        ? timeServerMapper[orgId.Value]
                        : null;

                    var peer = new Peer(id, name, ip, server);
                    AddItem(peer);
                }
            }
            catch (Exception e)
            {
                Log.ReadError(TableName, e);
            }
            finally
            {
                Close();
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        protected override void Update(Peer item)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareSql(UpdateSql);
                    Command.Parameters.Add(CreateParameter("@name", item.Name));
                    Command.Parameters.Add(CreateParameter("@ip", item.Ip));
                    Command.Parameters.Add(CreateParameter("@orgId", item.OrgId));
                    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();
                }
            }
        }
    }
}