// 
// 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.Collections.Generic;
using System.Linq;
using Ntp.Analyzer.Config.Node;
using Ntp.Analyzer.Data;
using Ntp.Analyzer.Import;
using Ntp.Analyzer.Objects;
using Ntp.Analyzer.Process.Log;
using Ntp.Common.Log;
using Ntp.Common.Process;

namespace Ntp.Analyzer.Process.Description
{
    /// <summary>
    /// Job which read statistics about peers and saves the result to a database.
    /// </summary>
    public sealed class PeerStatJob : JobDescription
    {
        public PeerStatJob(StatConfiguration config, LogBase log)
            : base(config, log)
        {
            this.config = config;
            readings = new List<PeerReading>();
            activities = new List<PeerActivity>();
            entries = new List<AssociationEntry>();
        }

        private readonly List<PeerActivity> activities;

        private readonly StatConfiguration config;
        private readonly List<AssociationEntry> entries;
        private readonly List<PeerReading> readings;
        private Host host;
        private List<Peer> peers;

        public override ThreadType ThreadType => ThreadType.MultiThreaded;

        public override string JobType => "Peer statistics";

        public override int Priority => 2;

        protected override void InternalExecute()
        {
            try
            {
                Initalize();
                Import();
                SaveResult();
            }
            catch (Exception e)
            {
                Log.PeerImportError(e);
            }
        }

        /// <summary>
        /// Import statistics.
        /// </summary>
        private void Import()
        {
            var bulk = config.Bulk == null
                ? new ReadingBulk(host.Name, config.TimeStamp)
                : DataFace.Instance.ReadingBulks.Single(b => b.Name == config.Bulk.Name);

            var importer = ImportFactory.CreatePeerImporter(config.ServerName, config.ServerType, host, Log);
            entries.AddRange(importer);

            // Read values
            try
            {
                importer.Execute();
            }
            catch (Exception e)
            {
                Log.PeerImportError(e);
                return;
            }

            // Generate statistics
            foreach (var entry in entries)
            {
                // Find peer in database.
                var currentEntry = entry;
                IEnumerable<Peer> peerList = peers.Where(p => p.Ip == currentEntry.Remote).ToList();
                Peer peer;

                if (peerList.Count() == 1)
                {
                    peer = peerList.Single();
                }
                else if (!peerList.Any())
                {
                    Log.PeerIpNotFound(entry);
                    continue;
                }
                else
                {
                    Log.PeerIpAmbiguous(entry);
                    continue;
                }

                var reading = new PeerReading(host, peer, bulk, entry);
                readings.Add(reading);

                // Update timestamp
                var activity = DataFace.Instance.PeerActivities.
                    SingleOrDefault(a => Equals(a.Host, reading.Host) && Equals(a.Peer, reading.Peer));

                if (activity != null)
                {
                    activity.LastActive = bulk.Time;
                }
                else
                {
                    activity = new PeerActivity(reading.Peer, host, bulk.Time);
                }

                activities.Add(activity);
            }
        }

        /// <summary>
        /// Initalize database context.
        /// </summary>
        private void Initalize()
        {
            // Clear any previouse readings
            entries.Clear();
            readings.Clear();
            activities.Clear();

            peers = DataFace.Instance.Peers.ToList();
            host = DataFace.Instance.Hosts.SingleOrDefault(h => h.Id == config.HostId);

            if (host == null)
            {
                Log.HostNotFound(config.HostId);
            }
        }

        /// <summary>
        /// Saves the result of the import to database.
        /// </summary>
        private void SaveResult()
        {
            foreach (var reading in readings)
            {
                DataFace.Instance.PeerReadings.Save(reading);
            }

            foreach (var activity in activities)
            {
                DataFace.Instance.PeerActivities.Save(activity);
            }

            foreach (var entry in entries)
            {
                DataFace.Instance.AssociationEntries.Delete(entry.Remote, entry.HostId);
                DataFace.Instance.AssociationEntries.Save(entry);
            }
        }
    }
}