//
// PeerDatabaseMapper.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 peer.
    /// </summary>
    public sealed class PeerDatabaseMapper : DatabaseMapper<Peer>
    {
        private readonly TimeServerDatabaseMapper timeServerMapper;

        /// <summary>
        /// Initializes a new instance of the <see cref="Ntp.Analyzer.Data.Mapper.PeerDatabaseMapper" /> class.
        /// </summary>
        /// <param name="timeServerMapper">Time server mapper.</param>
        internal PeerDatabaseMapper (TimeServerDatabaseMapper timeServerMapper, LogBase log)
            : base(log)
        {
            this.timeServerMapper = timeServerMapper;
        }

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

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

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

        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);" +
            "SELECT LAST_INSERT_ID();";
        private const string updateSql =
            "UPDATE peer SET name = @name, ip=@ip, orgId=@orgId WHERE id=@id";

        protected override void Insert (Peer item)
        {
            lock (Locker) {
                try {
                    Open ();

                    Command.CommandText = insertSql;
                    Command.Prepare ();

                    Command.Parameters.AddWithValue ("@name", item.Name);
                    Command.Parameters.AddWithValue ("@ip", item.Ip);
                    Command.Parameters.AddWithValue ("@orgId", (object)item.OrgId ?? (object)DBNull.Value);

                    object idObject = Command.ExecuteScalar ();
                    item.SetId (Convert.ToInt32 (idObject));
                } finally {
                    Close ();
                }
            }
        }

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

                    Command.CommandText = updateSql;
                    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.ExecuteNonQuery ();
                } finally {
                    Close ();
                }
            }
        }

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

                if (HasContent) {
                    foreach (Peer item in Content)
                        yield return item;

                    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;

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

                        Peer peer = new Peer (id, name, ip, server);
                        AddItem (peer);

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