//
// HostDatabaseMapper.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013-2016 Carsten Sonne Larsen
//
// 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 Ntp.Analyzer.Localize;
using Ntp.Log;
using Ntp.Analyzer.Objects;

namespace Ntp.Analyzer.Data.Sql
{
    /// <summary>
    /// ORM mapper for table host.
    /// </summary>
    public sealed class HostDatabaseMapper : SqlDatabaseMapper<Host>
    {
        internal HostDatabaseMapper(LogBase log)
            : base(log)
        {
        }

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

        private const string InsertSql =
            "INSERT INTO host(id, name, ip, orgId) VALUES(@id, @name, @ip, @orgId);";

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

        protected override bool UseCache
        {
            get { return true; }
        }

        protected override string TableName
        {
            get { return "host"; }
        }

        protected override string CreateSql
        {
            get
            {
                return
                    "CREATE TABLE host ( " +
                    "    id INT NOT NULL PRIMARY KEY, " +
                    "    name VARCHAR(30) NOT NULL, " +
                    "    ip VARCHAR(15) NOT NULL, " +
                    "    orgId INT " +
                    "){1};";
            }
        }

        protected override void ReadContent()
        {
            try
            {
                Open();
                Command.CommandText = PrepareSql(SelectSql);
                Reader = Command.ExecuteReader();

                while (Reader.Read())
                {
                    int id = Convert.ToInt32(Reader["id"]);
                    string name = Reader["name"].ToString();
                    string ip = Reader["ip"].ToString();
                    int? orgId = Reader["orgId"] != DBNull.Value
                        ? Convert.ToInt32(Reader["orgId"])
                        : (int?) null;
                    var host = new Host(id, name, ip, orgId, false);
                    AddItem(host);
                }
            }
            catch (Exception e)
            {
                Log.WriteLine(String.Format(
                    LogMessage.DatabaseTableError, LogMessage.DatabaseRead, TableName, e.Message),
                    Severity.Error);
                Log.WriteLine(e, Severity.Trace);
            }
            finally
            {
                Close();
            }
        }

        protected override void Insert(Host item)
        {
            lock (MapperLocker)
            {
                try
                {
                    Open();
                    Command.CommandText = PrepareInsertSql(InsertSql);
                    Command.Parameters.Add(CreateParameter("@id", item.Id));
                    Command.Parameters.Add(CreateParameter("@name", item.Name));
                    Command.Parameters.Add(CreateParameter("@ip", item.Ip));
                    Command.Parameters.Add(CreateParameter("@orgId", item.OrgId));
                    Command.Prepare();
                    Command.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    Log.WriteLine(String.Format(
                        LogMessage.DatabaseTableError, LogMessage.DatabaseInsert, TableName, e.Message),
                        Severity.Error);
                    Log.WriteLine(e, Severity.Trace);
                }
                finally
                {
                    Close();
                }
            }
        }

        protected override void Update(Host 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();
                    Command.ExecuteScalar();
                }
                catch (Exception e)
                {
                    Log.WriteLine(String.Format(
                        LogMessage.DatabaseTableError, LogMessage.DatabaseUpdate, TableName, e.Message),
                        Severity.Error);
                    Log.WriteLine(e, Severity.Trace);
                }
                finally
                {
                    Close();
                }
            }
        }
    }
}