//
// PeerStatJob.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 System.Collections.Generic;
using System.Linq;
using Ntp.Analyzer.Config.Stats;
using Ntp.Analyzer.Data;
using Ntp.Analyzer.Import;
using Ntp.Analyzer.Localize;
using Ntp.Analyzer.Objects;
using Ntp.Log;
using Ntp.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(PeerStatConfiguration 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 PeerStatConfiguration config;
        private readonly List<AssociationEntry> entries;
        private readonly List<PeerReading> readings;
        private Host host;
        private List<Peer> peers;

        public override ThreadType ThreadType
        {
            get { return ThreadType.MultiThreaded; }
        }

        public override string JobType
        {
            get { return "Peer statistics"; }
        }

        public override int Priority
        {
            get { return 2; }
        }

        protected override void InternalExecute()
        {
            try
            {
                Initalize();
                Import();
                SaveResult();
            }
            catch (Exception e)
            {
                Log.WriteLine(String.Format(LogMessage.PeerImportError, e.Message), Severity.Warn);
                Log.WriteLine(e, Severity.Trace);
            }
        }

        /// <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.WriteLine(String.Format(LogMessage.HostNotFound, config.HostId), Severity.Warn);
            }
        }

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

            Importer<AssociationEntry> importer = ImportFactory.CreatePeerImporter(config.ServerName, config.ServerType,
                host, Log);
            entries.AddRange(importer);

            // Read values
            try
            {
                importer.Execute();
            }
            catch (Exception e)
            {
                Log.WriteLine(String.Format(LogMessage.PeerImportError, e.Message), Severity.Warn);
                Log.WriteLine(e, Severity.Trace);
                return;
            }

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

                if (peerList.Count() == 1)
                {
                    peer = peerList.Single();
                }
                else if (!peerList.Any())
                {
                    Log.WriteLine(String.Format(LogMessage.PeerIpNotFound, entry.Remote), Severity.Warn);
                    continue;
                }
                else
                {
                    Log.WriteLine(String.Format(LogMessage.PeerIpAmbiguous, entry.Remote), Severity.Warn);
                    continue;
                }

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

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

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

                activities.Add(activity);
            }
        }

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

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

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