//
// HostDatabaseMapper.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013 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 System.Collections.Generic;
using MySql.Data.MySqlClient;
using Ntp.Analyzer.Log;
using Ntp.Analyzer.Objects;

namespace Ntp.Analyzer.Data.Static
{
    /// <summary>
    /// ORM mapper for table host.
    /// </summary>
    public sealed class HostDatabaseMapper : DatabaseMapper<Host>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Ntp.Analyzer.Data.Mapper.HostDatabaseMapper" /> class.
        /// </summary>
        internal HostDatabaseMapper (LogBase log)
            : base(log)
        {
        }

        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 " +
                    ") ENGINE=INNODB;";                
            }
        }

        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);";

        protected override void Insert (Host item)
        {
            lock (Locker) {
                try {
                    Open ();
                    Command.CommandText = insertSql;
                    Command.Prepare ();
                    Command.Parameters.AddWithValue ("@id", item.Id);
                    Command.Parameters.AddWithValue ("@name", item.Name);
                    Command.Parameters.AddWithValue ("@ip", item.Ip);
                    Command.Parameters.AddWithValue ("@orgId", (object)item.OrgId ?? (object)DBNull.Value);
                    Command.ExecuteNonQuery ();
                } finally {
                    Close ();
                }
            }
        }

        protected override void Update (Host item)
        {
            lock (Locker) {
                try {
                    Open ();

                    Command.CommandText = "UPDATE host SET name = @name, ip=@ip, orgId=@orgId WHERE id=@id";
                    Command.Prepare ();

                    Command.Parameters.AddWithValue ("@name", item.Name);
                    Command.Parameters.AddWithValue ("@ip", item.Ip);
                    Command.Parameters.AddWithValue ("@orgId", (object)item.OrgId ?? (object)DBNull.Value);
                    Command.Parameters.AddWithValue ("@id", item.Id);
                    Command.ExecuteScalar ();
                } finally {
                    Close ();
                }
            }
        }

        /// <summary>
        /// Read all data from table in a sequential manner.
        /// </summary>
        /// <returns>The enumerator.</returns>
        public override IEnumerator<Host> GetEnumerator ()
        {
            lock (Locker) {

                if (HasContent) {
                    foreach (Host host in Content)
                        yield return host;

                    yield break;
                }

                try {
                    Open ();
                    Command.CommandText = 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 ?
                            (int?)Convert.ToInt32 (Reader ["orgId"]) : (int?)null;
                            
                        Host host = new Host (id, name, ip, orgId, false);
                        AddItem (host);

                        yield return host;
                    }
                } finally {
                    Close ();
                }
            }
        }
    }
}
