//
// SourcePeerDatabaseMapper.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 System.Net;
using MySql.Data.MySqlClient;
using Ntp.Analyzer.Log;
using Ntp.Analyzer.Objects;
using Ntp.Analyzer.Objects.Packet;

namespace Ntp.Analyzer.Data.Static
{
    /// <summary>
    /// ORM mapper for table sourcePeer.
    /// </summary>
    public sealed class SourcePeerDatabaseMapper : DatabaseMapper<SourcePeer>
    {
        private readonly PeerDatabaseMapper peerMapper;

        internal SourcePeerDatabaseMapper (PeerDatabaseMapper peerMapper, LogBase log)
            : base(log)
        {
            this.peerMapper = peerMapper;
        }

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

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

        protected override string CreateSql {
            get {
                return String.Empty;                    
            }
        }

        private const string selectSql =
            "SELECT id, ip, peerId FROM sourcePeer;";
        private const string insertSql =
            "INSERT INTO sourcePeer(ip, peerId) VALUES(?ip, ?peerId);" +
            "SELECT LAST_INSERT_ID();";

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

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

                    Command.Parameters.AddWithValue ("?ip", item.Ip);
                    Command.Parameters.AddWithValue ("?peerId", item.Peer != null ? (object)item.Peer.Id : DBNull.Value);

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

        protected override void Update (SourcePeer item)
        {
            throw new NotImplementedException ();
        }

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

                if (HasContent) {
                    foreach (SourcePeer 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 ip = Reader ["ip"].ToString ();
                        int? peerId = Reader ["peerId"] != DBNull.Value ? Convert.ToInt32 (Reader ["peerId"]) : (int?)null;
                        Peer peer = peerId.HasValue ? peerMapper [peerId.Value] : null;

                        SourcePeer sourcePeer = new SourcePeer (id, IPAddress.Parse (ip), peer);

                        AddItem (sourcePeer);

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