// 
// 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.Drawing;
using NPlot;
using Ntp.Analyzer.Data;
using Ntp.Analyzer.Data.Sql;
using Ntp.Analyzer.Interface;
using Ntp.Analyzer.Objects;

namespace Ntp.Analyzer.Graph
{
    public sealed class PeerGraph : DispersionGraph
    {
        public PeerGraph(IPeerGraphConfiguration configuratation, Host host, Peer peer)
            : base(configuratation)
        {
            config = configuratation;
            this.host = host;
            this.peer = peer;

            timedReading = new Dictionary<DateTime, HostReading>();
        }

        private readonly List<double> balance = new List<double>();
        private readonly IPeerGraphConfiguration config;
        private readonly List<double> delay = new List<double>();
        private readonly Host host;
        private readonly Peer peer;
        private readonly Dictionary<DateTime, HostReading> timedReading;

        protected override string YLabel => "Milliseconds";

        protected override void AddPlots()
        {
            base.AddPlots();

            if (config.Delay.HasValue)
            {
                var delayPlot = SetupPlot("Delay", Color.DarkOrange, Time, delay);
                Surface.Add(delayPlot, PlotSurface2D.XAxisPosition.Bottom, PlotSurface2D.YAxisPosition.Left);
            }

            if (config.Balance.HasValue)
            {
                var balancePlot = SetupPlot("Balanced offset", Color.DarkViolet, Time, balance);
                Surface.Add(balancePlot, PlotSurface2D.XAxisPosition.Bottom, PlotSurface2D.YAxisPosition.Left);
            }
        }

        protected override void LoadData()
        {
            FilteredSqlDatabaseMapper<PeerReading> peerMapper = DataFace.Instance.PeerReadings;
            peerMapper.FilterHost = host;
            peerMapper.FilterPeer = peer;
            peerMapper.FilterTime = DateTime.UtcNow.Subtract(GraphTimeSpan);

            if (config.Balance.HasValue)
            {
                foreach (var reading in peerMapper)
                {
                    Time.Add(config.GraphTime == DateTimeKind.Local ? reading.LocalTime : reading.UtcTime);

                    if (config.Offset.HasValue) Offset.Add(reading.Offset*config.Offset.Value);
                    else Offset.Add(0.0);

                    if (config.Jitter.HasValue) Jitter.Add(reading.Jitter*config.Jitter.Value);
                    else Jitter.Add(0.0);

                    if (config.Delay.HasValue) delay.Add(reading.Delay*config.Delay.Value);
                    else delay.Add(0.0);

                    balance.Add(0.0);
                }
            }
            else
            {
                FilteredSqlDatabaseMapper<HostReading> hostMapper = DataFace.Instance.HostReadings;
                hostMapper.FilterHost = host;
                hostMapper.FilterTime = DateTime.UtcNow.Subtract(GraphTimeSpan);

                // Prepare balance data
                foreach (var hostReading in hostMapper)
                {
                    var indexTime = config.GraphTime == DateTimeKind.Local
                        ? hostReading.RoundedLocalTime
                        : hostReading.RoundedUtcTime;

                    if (!timedReading.ContainsKey(indexTime))
                        timedReading.Add(indexTime, hostReading);
                }

                // Add
                foreach (var reading in peerMapper)
                {
                    Time.Add(config.GraphTime == DateTimeKind.Local ? reading.LocalTime : reading.UtcTime);

                    if (config.Offset.HasValue) Offset.Add(reading.Offset*config.Offset.Value);
                    else Offset.Add(0.0);

                    if (config.Jitter.HasValue) Jitter.Add(reading.Jitter*config.Jitter.Value);
                    else Jitter.Add(0.0);

                    if (config.Delay.HasValue) delay.Add(reading.Delay*config.Delay.Value);
                    else delay.Add(0.0);

                    var indexTime = config.GraphTime == DateTimeKind.Local
                        ? reading.RoundedLocalTime
                        : reading.RoundedUtcTime;

                    if (timedReading.ContainsKey(indexTime))
                        balance.Add(reading.Offset - timedReading[indexTime].Offset);
                    else
                        balance.Add(0.0);
                }
            }

            if (config.FilterFactor.HasValue)
                CleanSeries();
        }

        protected override void PreRender()
        {
            base.PreRender();

            Surface.Title = config.GetTitle(peer);
        }

        /// <summary>
        /// Cleans the value series from values out side boundaries.
        /// </summary>
        private void CleanSeries()
        {
            double totalOffset = 0.0;
            double totalJitter = 0.0;
            double totalDelay = 0.0;
            double totalBalance = 0.0;

            // Calculate mean value
            for (int i = 0; i < Time.Count; i++)
            {
                totalOffset += Math.Abs(Offset[i]);
                totalJitter += Math.Abs(Jitter[i]);
                totalDelay += Math.Abs(delay[i]);
                totalBalance += Math.Abs(balance[i]);
            }

            double avgOffset = totalOffset/Time.Count;
            double avgJitter = totalJitter/Time.Count;
            double avgDelay = totalDelay/Time.Count;
            double avgBalance = totalBalance/Time.Count;

            var indexes = new List<int>();

            // Find invalid values
            for (int i = 0; i < Time.Count; i++)
            {
                if (Math.Abs(Offset[i]) > avgOffset*config.FilterFactor ||
                    Math.Abs(Jitter[i]) > avgJitter*config.FilterFactor ||
                    Math.Abs(delay[i]) > avgDelay*config.FilterFactor ||
                    Math.Abs(balance[i]) > avgBalance*config.FilterFactor)
                {
                    indexes.Add(i);
                }
            }

            // Remove invalid values
            for (int i = indexes.Count - 1; i >= 0; i--)
            {
                Time.RemoveAt(indexes[i]);
                Offset.RemoveAt(indexes[i]);
                Jitter.RemoveAt(indexes[i]);
                delay.RemoveAt(indexes[i]);
                balance.RemoveAt(indexes[i]);
            }
        }
    }
}