//
// TrafficGraphConfiguration.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.Destination;
using Ntp.Analyzer.Interface;
using Ntp.Analyzer.Localize;
using Ntp.Analyzer.Objects;
using Ntp.Config;

namespace Ntp.Analyzer.Config.Graph
{
    public sealed class TrafficGraphConfiguration : GraphBaseConfiguration, ITrafficGraphConfiguration
    {
        private TrafficGraphConfiguration(
            HostConfiguration server,
            string configName,
            int indentLevel,
            int frequency,
            bool initialRun,
            bool fixedRun,
            string title,
            int width,
            int height,
            int timespan,
            double received,
            double ignored,
            double dropped,
            double sent,
            double notSent,
            double receivedAvg,
            double ignoredAvg,
            double droppedAvg,
            double sentAvg,
            double notSentAvg,
            int plotInterval,
            int packetRate,
            DestinationCollection destinations,
            WebLinkCollection links)
            : base(
                server,
                configName,
                indentLevel,
                frequency,
                initialRun,
                fixedRun,
                title,
                width,
                height,
                timespan,
                0.0,
                destinations,
                links)
        {
            this.received = received;
            this.ignored = ignored;
            this.dropped = dropped;
            this.sent = sent;
            this.notSent = notSent;
            this.receivedAvg = receivedAvg;
            this.ignoredAvg = ignoredAvg;
            this.droppedAvg = droppedAvg;
            this.sentAvg = sentAvg;
            this.notSentAvg = notSentAvg;
            this.plotInterval = plotInterval;
            this.packetRate = packetRate;
        }

        public const string Identifier = ConfigurationKeyword.TrafficGraph;
        private const int DefaultPlotInterval = 15;
        private const int DefaultPacketRate = 1;

        // TODO: Add unit
        private static readonly String[] Params =
        {
            ConfigurationKeyword.TrafficGraph,
            ConfigurationKeyword.Frequency,
            ConfigurationKeyword.InitialRun,
            ConfigurationKeyword.FixedRun,
            ConfigurationKeyword.GraphTitle,
            ConfigurationKeyword.GraphWidth,
            ConfigurationKeyword.GraphHeight,
            ConfigurationKeyword.GraphTimespan,
            ConfigurationKeyword.TrafficGraphReceived,
            ConfigurationKeyword.TrafficGraphIgnored,
            ConfigurationKeyword.TrafficGraphDropped,
            ConfigurationKeyword.TrafficGraphSent,
            ConfigurationKeyword.TrafficGraphNotSent,
            ConfigurationKeyword.TrafficGraphAvgReceived,
            ConfigurationKeyword.TrafficGraphAvgIgnored,
            ConfigurationKeyword.TrafficGraphAvgDropped,
            ConfigurationKeyword.TrafficGraphAvgSent,
            ConfigurationKeyword.TrafficGraphAvgNotSent,
            ConfigurationKeyword.TrafficGraphPlotInterval,
            ConfigurationKeyword.TrafficGraphPacketRate,
            FileCollection.Identifier,
            WebLinkCollection.Identifier
        };

        private readonly double dropped;
        private readonly double droppedAvg;
        private readonly double ignored;
        private readonly double ignoredAvg;
        private readonly double notSent;
        private readonly double notSentAvg;
        private readonly int packetRate;
        private readonly int plotInterval;
        private readonly double received;
        private readonly double receivedAvg;
        private readonly double sent;
        private readonly double sentAvg;

        protected override IEnumerable<Object> Items
        {
            get
            {
                var items = new List<object> {ConfigName, Frequency};

                if (ShowDefault || (!ShowDefault && InitialRun != DefaultInitialRun))
                    items.Add(InitialRun);

                if (ShowDefault || (!ShowDefault && FixedRun != DefaultFixedRun))
                    items.Add(FixedRun);

                if (ShowDefault || (!ShowDefault && Title != DefaultTitle))
                    items.Add(Title);

                if (ShowDefault || (!ShowDefault && Width != DefaultWidth))
                    items.Add(Width);

                if (ShowDefault || (!ShowDefault && Height != DefaultHeight))
                    items.Add(Height);

                if (ShowDefault || (!ShowDefault && Timespan != DefaultTimespan))
                    items.Add(Timespan);

                if (ShowDefault || (!ShowDefault && Received != DefaultValue))
                    items.Add(Received);

                if (ShowDefault || (!ShowDefault && Ignored != DefaultValue))
                    items.Add(Ignored);

                if (ShowDefault || (!ShowDefault && Dropped != DefaultValue))
                    items.Add(Dropped);

                if (ShowDefault || (!ShowDefault && Sent != DefaultValue))
                    items.Add(Sent);

                if (ShowDefault || (!ShowDefault && NotSent != DefaultValue))
                    items.Add(NotSent);

                if (ShowDefault || (!ShowDefault && ReceivedAvg != DefaultValue))
                    items.Add(ReceivedAvg);

                if (ShowDefault || (!ShowDefault && IgnoredAvg != DefaultValue))
                    items.Add(IgnoredAvg);

                if (ShowDefault || (!ShowDefault && DroppedAvg != DefaultValue))
                    items.Add(DroppedAvg);

                if (ShowDefault || (!ShowDefault && SentAvg != DefaultValue))
                    items.Add(SentAvg);

                if (ShowDefault || (!ShowDefault && NotSentAvg != DefaultValue))
                    items.Add(NotSentAvg);

                if (ShowDefault || (!ShowDefault && PlotInterval != DefaultPlotInterval))
                    items.Add(PlotInterval);

                if (ShowDefault || (!ShowDefault && PacketRate != DefaultPacketRate))
                    items.Add(PacketRate);

                items.Add(Destinations);

                if (ShowDefault || (!ShowDefault &&
                                    Destinations.Count() == 1 && Links.Count() == 1 &&
                                    Destinations.First().Link != Links.First().Link))
                    items.Add(Links);

                return items.ToArray();
            }
        }

        public double Received
        {
            get { return received; }
        }

        public double Ignored
        {
            get { return ignored; }
        }

        public double Dropped
        {
            get { return dropped; }
        }

        public double Sent
        {
            get { return sent; }
        }

        public double NotSent
        {
            get { return notSent; }
        }

        public double ReceivedAvg
        {
            get { return receivedAvg; }
        }

        public double IgnoredAvg
        {
            get { return ignoredAvg; }
        }

        public double DroppedAvg
        {
            get { return droppedAvg; }
        }

        public double SentAvg
        {
            get { return sentAvg; }
        }

        public double NotSentAvg
        {
            get { return notSentAvg; }
        }

        public int PlotInterval
        {
            get { return plotInterval; }
        }

        public int PacketRate
        {
            get { return packetRate; }
        }

        public override string GetTitle(NamedObject namedObject)
        {
            return Title;
        }

        /// <summary>
        /// Gets the link to use when referred to from web pages.
        /// </summary>
        /// <returns>The link.</returns>
        /// <param name="owner">Owner.</param>
        /// <param name="postfix">Text to prepend</param>
        public override string GetLink(GraphSetConfiguration owner, string postfix)
        {
            int index = owner.LinkIndex;

            if (index <= 0 || index > Links.Destinations.Count())
                throw new ConfigurationException(
                    String.Format(ConfigurationMessage.TrafficGraphLinkIndex1, index));

            return WebPath + Links.Destinations[index - 1].Link;
        }

        /// <summary>
        /// Gets the alternative name when referred to from web pages.
        /// </summary>
        /// <returns>The alternate name.</returns>
        /// <param name="owner">Owner.</param>
        /// <param name="postfix">Text to prepend</param>
        public override string GetAltName(GraphSetConfiguration owner, string postfix)
        {
            int index = owner.LinkIndex;

            if (index <= 0 || index > Links.Destinations.Count())
                throw new ConfigurationException(
                    String.Format(ConfigurationMessage.TrafficGraphLinkIndex2, index));

            string name = Links.Destinations[index - 1].Link;

            // remove any path from name
            int pos = name.LastIndexOf('/');
            name = pos != -1 ? name.Remove(0, pos + 1) : name;

            return name;
        }

        public override string GetPageLink(GraphSetConfiguration graphSet, string prefix, string postfix)
        {
            return WebPath + prefix + GetAltName(graphSet, postfix).Replace('.', '-') + ".html";
        }

        public override string ToString()
        {
            var list = new List<String> {ConfigurationKeyword.TrafficGraph, ConfigurationKeyword.Frequency};

            if (ShowDefault || (!ShowDefault && InitialRun != DefaultInitialRun))
                list.Add(ConfigurationKeyword.InitialRun);

            if (ShowDefault || (!ShowDefault && FixedRun != DefaultFixedRun))
                list.Add(ConfigurationKeyword.FixedRun);

            if (ShowDefault || (!ShowDefault && Title != DefaultTitle))
                list.Add(ConfigurationKeyword.GraphTitle);

            if (ShowDefault || (!ShowDefault && Width != DefaultWidth))
                list.Add(ConfigurationKeyword.GraphWidth);

            if (ShowDefault || (!ShowDefault && Height != DefaultHeight))
                list.Add(ConfigurationKeyword.GraphHeight);

            if (ShowDefault || (!ShowDefault && Timespan != DefaultTimespan))
                list.Add(ConfigurationKeyword.GraphTimespan);

            if (ShowDefault || (!ShowDefault && Received != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphReceived);

            if (ShowDefault || (!ShowDefault && Ignored != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphIgnored);

            if (ShowDefault || (!ShowDefault && Dropped != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphDropped);

            if (ShowDefault || (!ShowDefault && Sent != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphSent);

            if (ShowDefault || (!ShowDefault && NotSent != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphNotSent);

            if (ShowDefault || (!ShowDefault && ReceivedAvg != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphAvgReceived);

            if (ShowDefault || (!ShowDefault && IgnoredAvg != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphAvgIgnored);

            if (ShowDefault || (!ShowDefault && DroppedAvg != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphAvgDropped);

            if (ShowDefault || (!ShowDefault && SentAvg != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphAvgSent);

            if (ShowDefault || (!ShowDefault && NotSentAvg != DefaultValue))
                list.Add(ConfigurationKeyword.TrafficGraphAvgNotSent);

            if (ShowDefault || (!ShowDefault && PlotInterval != DefaultPlotInterval))
                list.Add(ConfigurationKeyword.TrafficGraphPlotInterval);

            if (ShowDefault || (!ShowDefault && PacketRate != DefaultPacketRate))
                list.Add(ConfigurationKeyword.TrafficGraphPacketRate);

            list.Add(FileCollection.Identifier);

            if (ShowDefault || (!ShowDefault &&
                                Destinations.Count() == 1 && Links.Count() == 1 &&
                                Destinations.First().Link != Links.First().Link))
                list.Add(WebLinkCollection.Identifier);

            return ConfigText(list.ToArray(), Items);
        }

        public static TrafficGraphConfiguration Create(
            HostConfiguration server,
            ConfigurationBlock config)
        {
            Dictionary<String, String> options = GetOptions(Params, config);

            return new TrafficGraphConfiguration(
                server,
                GetOptionConfigName(options, ConfigurationKeyword.TrafficGraph, Identifier, true),
                config.IndentLevel,
                GetOptionInteger(options, ConfigurationKeyword.Frequency, Identifier, true),
                GetOptionBoolean(options, ConfigurationKeyword.InitialRun, Identifier, false, DefaultInitialRun),
                GetOptionBoolean(options, ConfigurationKeyword.FixedRun, Identifier, false, DefaultFixedRun),
                GetOptionString(options, ConfigurationKeyword.GraphTitle, Identifier, false, DefaultTitle),
                GetOptionInteger(options, ConfigurationKeyword.GraphWidth, Identifier, false, DefaultWidth),
                GetOptionInteger(options, ConfigurationKeyword.GraphHeight, Identifier, false, DefaultHeight),
                GetOptionInteger(options, ConfigurationKeyword.GraphTimespan, Identifier, false, DefaultTimespan),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphReceived, Identifier, false),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphIgnored, Identifier, false),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphDropped, Identifier, false),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphSent, Identifier, false),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphNotSent, Identifier, false),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphAvgReceived, Identifier, false),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphAvgIgnored, Identifier, false),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphAvgDropped, Identifier, false),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphAvgSent, Identifier, false),
                GetOptionDouble(options, ConfigurationKeyword.TrafficGraphAvgNotSent, Identifier, false),
                GetOptionInteger(options, ConfigurationKeyword.TrafficGraphPlotInterval, Identifier, false,
                    DefaultPlotInterval),
                GetOptionInteger(options, ConfigurationKeyword.TrafficGraphPacketRate, Identifier, false,
                    DefaultPacketRate),
                FileCollection.Create(server, config),
                WebLinkCollection.Create(server, config));
        }
    }
}