//
// HostGraph.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.Drawing;
using System.Globalization;
using System.Linq;
using NPlot;
using Ntp.Analyzer.Data;
using Ntp.Analyzer.Objects;
using Ntp.Analyzer.Config.Graph;
using Ntp.Analyzer.Graph.Interface;
using Ntp.Analyzer.Data.Static;

namespace Ntp.Analyzer.Graph
{
    public sealed class HostGraph : DispersionGraph
    {
        private readonly IHostGraphConfiguration config;
        private readonly List<Double> frequency = new List<Double> ();
        private readonly Host host;
        private readonly List<Double> stability = new List<Double> ();

        public HostGraph (IHostGraphConfiguration configuratation, Host host)
            : base(configuratation)
        {
            config = configuratation;
            this.host = host;
            frequency = new List<Double> ();
            stability = new List<Double> ();
        }

        protected override string YLabel {
            get { return "Milliseconds"; }
        }

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

            foreach (HostReading reading in dataMapper) {
                Time.Add (reading.Time);
                Offset.Add (reading.Offset * config.Offset);
                Jitter.Add (reading.Jitter * config.Jitter);
                frequency.Add (reading.Frequency * config.Gfrequency);
                stability.Add (reading.Stability * config.Stability);
            }

            if (config.FilterFactor != 0.0)
                CleanSeries ();
        }

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

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

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

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

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

        /// <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 += System.Math.Abs (Offset [i]);
                totalJitter += System.Math.Abs (Jitter [i]);
                totalFrequency += System.Math.Abs (frequency [i]);
                totalStability += System.Math.Abs (stability [i]);
            }

            double avgOffset = totalOffset / Time.Count;
            double avgJitter = totalJitter / Time.Count;
            double avgFrequency = totalFrequency / Time.Count;
            double avgStability = totalStability / Time.Count;

            List<Int32> indexes = new List<Int32> ();

            // Find invalid values
            for (int i = 0; i < Time.Count; i++) {
                if (System.Math.Abs (Offset [i]) > avgOffset * config.FilterFactor ||
                    System.Math.Abs (Jitter [i]) > avgJitter * config.FilterFactor ||
                    System.Math.Abs (frequency [i]) > avgFrequency * config.FilterFactor ||
                    System.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]);
            }
        }
    }
}