// 
// 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;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using NPlot;
using Ntp.Analyzer.Export;
using Ntp.Analyzer.Interface;
using PlotSurface2D = NPlot.Bitmap.PlotSurface2D;

namespace Ntp.Analyzer.Graph
{
    public abstract class GraphBase : IStreamGenerator
    {
        protected GraphBase(IGraphBaseConfiguration baseConfig)
        {
            this.baseConfig = baseConfig;
            destinations = new List<StreamDestination>(baseConfig.Locations);
        }

        private static readonly object Locker = new object();
        private readonly IGraphBaseConfiguration baseConfig;
        private readonly List<StreamDestination> destinations;

        protected abstract string YLabel { get; }

        protected PlotSurface2D Surface { get; private set; }

        protected TimeSpan GraphTimeSpan => new TimeSpan(baseConfig.Timespan, 0, 0, 0);

        public string ImageFileExtension => "png";

        public IEnumerable<StreamDestination> Destinations => destinations;

        public Stream Generate()
        {
            Surface = new PlotSurface2D(baseConfig.Width, baseConfig.Height);

            // Only one loader at the time
            lock (Locker)
            {
                LoadData();
            }

            var titleFont = new Font("Arial", 12);
            var axisFont = new Font("Arial", 10);
            var legendFont = new Font("Arial", 10);
            var tickFont = new Font("Arial", 8);

            // Prepare PlotSurface:
            Surface.Clear();
            Surface.Title = baseConfig.Title;
            Surface.TitleFont = titleFont;
            Surface.SmoothingMode = SmoothingMode.HighQuality;
            Surface.BackColor = Color.White;
            Surface.Add(new Grid(), NPlot.PlotSurface2D.XAxisPosition.Bottom, NPlot.PlotSurface2D.YAxisPosition.Left);

            AddPlots();

            // Prepare axis
            Surface.XAxis1.Label = string.Empty;
            Surface.XAxis1.LabelFont = axisFont;
            Surface.XAxis1.TickTextFont = tickFont;
            Surface.XAxis1.TicksLabelAngle = 0;
            Surface.XAxis1.TickTextNextToAxis = true;
            Surface.XAxis1.FlipTicksLabel = true;
            Surface.XAxis1.LabelOffset = 95;
            Surface.XAxis1.LabelOffsetAbsolute = true;
            Surface.XAxis1.NumberFormat = baseConfig.Timespan <= 2 ? "HH" : "MMMM d";
            Surface.YAxis1.Label = YLabel;
            Surface.YAxis1.LabelFont = axisFont;
            Surface.YAxis1.LabelOffsetScaled = true;
            Surface.YAxis1.TickTextFont = tickFont;
            Surface.YAxis1.NumberFormat = "{0:####0.00}";

            if (Surface.YAxis2 != null)
            {
                Surface.YAxis2.Label = "Value";
                Surface.YAxis2.LabelFont = axisFont;
                Surface.YAxis2.TickTextFont = tickFont;
                Surface.YAxis2.NumberFormat = "{0:####0.00}";
            }

            // Add legend
            var legend = new Legend {Font = legendFont};
            legend.AttachTo(NPlot.PlotSurface2D.XAxisPosition.Top, NPlot.PlotSurface2D.YAxisPosition.Left);
            legend.VerticalEdgePlacement = Legend.Placement.Inside;
            legend.HorizontalEdgePlacement = Legend.Placement.Inside;
            legend.BorderStyle = LegendBase.BorderType.Line;
            legend.BackgroundColor = Color.White;
            legend.XOffset = 20;
            legend.YOffset = 15;
            Surface.Legend = legend;
            Surface.LegendZOrder = 10;

            PreRender();

            return Render();
        }

        public Stream Render()
        {
            var stream = new MemoryStream();

            if (Surface == null)
                return stream;

            // Only one rendering at the time
            lock (Locker)
            {
                using (var b = new Bitmap(baseConfig.Width, baseConfig.Height))
                using (var g = Graphics.FromImage(b))
                {
                    g.FillRectangle(new Pen(Color.White).Brush, 0, 0, b.Width, b.Height);
                    Surface.Draw(Graphics.FromImage(b), new Rectangle(0, 0, b.Width, b.Height));

                    b.Save(stream, ImageFormat.Png);
                }

                // Force garbage collection
                GC.Collect();
            }

            return stream;
        }

        protected abstract void AddPlots();

        protected abstract void LoadData();

        protected virtual void PreRender()
        {
        }

        protected LinePlot SetupPlot(string name, Color color, IList time, IList data)
        {
            var plot = new LinePlot
            {
                AbscissaData = time,
                DataSource = data,
                Color = color,
                Shadow = false,
                Label = name
            };

            return plot;
        }
    }
}