// 
// 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 System.Globalization;
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 HostGraph : DispersionGraph
    {
        public HostGraph(IHostGraphConfiguration configuratation, Host host)
            : base(configuratation)
        {
            config = configuratation;
            this.host = host;
            frequency = new List<double>();
            stability = new List<double>();
        }

        private readonly IHostGraphConfiguration config;
        private readonly List<double> frequency;
        private readonly Host host;
        private readonly List<double> stability;

        protected override string YLabel => "Milliseconds";

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

            string freqDesc = config.Gfrequency.HasValue
                ? " x " + config.Gfrequency.Value.ToString("0.00", CultureInfo.InvariantCulture)
                : string.Empty;

            var frequencyPlot = SetupPlot("Frequency" + freqDesc, Color.Green, Time, frequency);
            var stabilityPlot = SetupPlot("Stability", Color.Black, Time, stability);

            if (config.Stability.HasValue)
                Surface.Add(stabilityPlot, PlotSurface2D.XAxisPosition.Bottom, PlotSurface2D.YAxisPosition.Left);

            if (config.Gfrequency.HasValue)
                Surface.Add(frequencyPlot, PlotSurface2D.XAxisPosition.Bottom, PlotSurface2D.YAxisPosition.Left);
        }

        protected override void LoadData()
        {
            FilteredSqlDatabaseMapper<HostReading> dataMapper = DataFace.Instance.HostReadings;
            dataMapper.FilterHost = host;
            dataMapper.FilterTime = DateTime.UtcNow.Subtract(GraphTimeSpan);

            foreach (var reading in dataMapper)
            {
                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.Gfrequency.HasValue) frequency.Add(reading.Frequency*config.Gfrequency.Value);
                else frequency.Add(0.0);

                if (config.Stability.HasValue) stability.Add(reading.Stability*config.Stability.Value);
                else stability.Add(0.0);
            }

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

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

            // Calculate mean value
            for (int i = 0; i < Time.Count; i++)
            {
                totalOffset += Math.Abs(Offset[i]);
                totalJitter += Math.Abs(Jitter[i]);
                totalFrequency += Math.Abs(frequency[i]);
                totalStability += Math.Abs(stability[i]);
            }

            double avgOffset = totalOffset/Time.Count;
            double avgJitter = totalJitter/Time.Count;
            double avgFrequency = totalFrequency/Time.Count;
            double avgStability = totalStability/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(frequency[i]) > avgFrequency*config.FilterFactor ||
                    Math.Abs(stability[i]) > avgStability*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]);
                frequency.RemoveAt(indexes[i]);
                stability.RemoveAt(indexes[i]);
            }
        }
    }
}