//
// HostGraphConfiguration.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
{
    /// <summary>
    /// Host graph configuration used when creating <seealso cref="Ntp.Analyzer.Graph.HostGraph" />.
    /// </summary>
    public sealed class HostGraphConfiguration : DispersionGraphConfiguration, IHostGraphConfiguration
    {
        private HostGraphConfiguration(
            HostConfiguration server,
            string configName,
            int indentLevel,
            int frequency,
            bool initialRun,
            bool fixedRun,
            string title,
            int width,
            int height,
            int timespan,
            double filterFactor,
            double gfrequency,
            double stability,
            double jitter,
            double offset,
            DestinationCollection destinations,
            WebLinkCollection links)
            : base(
                server,
                configName,
                indentLevel,
                frequency,
                initialRun,
                fixedRun,
                title,
                width,
                height,
                timespan,
                filterFactor,
                offset,
                jitter,
                destinations,
                links)
        {
            this.stability = stability;
            this.gfrequency = gfrequency;
        }

        public const string Identifier = ConfigurationKeyword.HostGraph;

        private static readonly String[] Params =
        {
            ConfigurationKeyword.HostGraph,
            ConfigurationKeyword.Frequency,
            ConfigurationKeyword.InitialRun,
            ConfigurationKeyword.FixedRun,
            ConfigurationKeyword.GraphTitle,
            ConfigurationKeyword.GraphWidth,
            ConfigurationKeyword.GraphHeight,
            ConfigurationKeyword.GraphTimespan,
            ConfigurationKeyword.GraphFilterFactor,
            ConfigurationKeyword.HostGraphGFrequency,
            ConfigurationKeyword.HostGraphStability,
            ConfigurationKeyword.GraphJitter,
            ConfigurationKeyword.GraphOffset,
            FileCollection.Identifier,
            WebLinkCollection.Identifier
        };

        private readonly double gfrequency;
        private readonly double stability;

        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 && FilterFactor != DefaultValue))
                    items.Add(FilterFactor);

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

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

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

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

                items.Add(Destinations);

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

                return items.ToArray();
            }
        }

        /// <summary>
        /// Gets the stability multiplication factor.
        /// </summary>
        /// <value>The stability.</value>
        public double Stability
        {
            get { return stability; }
        }

        /// <summary>
        /// Gets the frequency factor.
        /// </summary>
        /// <remarks>
        /// Frequency factor is obtained from NTP hosts.
        /// </remarks>
        /// <value>The frequency.</value>
        public double Gfrequency
        {
            get { return gfrequency; }
        }

        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.HostGraphLinkIndex1, 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.HostGraphLinkIndex2, 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.HostGraph, 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 && FilterFactor != DefaultValue))
                list.Add(ConfigurationKeyword.GraphFilterFactor);

            if (ShowDefault || (!ShowDefault && Gfrequency != DefaultValue))
                list.Add(ConfigurationKeyword.HostGraphGFrequency);

            if (ShowDefault || (!ShowDefault && Stability != DefaultValue))
                list.Add(ConfigurationKeyword.HostGraphStability);

            if (ShowDefault || (!ShowDefault && Jitter != DefaultValue))
                list.Add(ConfigurationKeyword.GraphJitter);

            if (ShowDefault || (!ShowDefault && Offset != DefaultValue))
                list.Add(ConfigurationKeyword.GraphOffset);

            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 HostGraphConfiguration Create(
            HostConfiguration server,
            ConfigurationBlock config)
        {
            Dictionary<String, String> options = GetOptions(Params, config);

            return new HostGraphConfiguration(
                server,
                GetOptionConfigName(options, ConfigurationKeyword.HostGraph, 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.GraphFilterFactor, Identifier, false, DefaultValue),
                GetOptionDouble(options, ConfigurationKeyword.HostGraphGFrequency, Identifier, false, DefaultValue),
                GetOptionDouble(options, ConfigurationKeyword.HostGraphStability, Identifier, false, DefaultValue),
                GetOptionDouble(options, ConfigurationKeyword.GraphJitter, Identifier, false, DefaultValue),
                GetOptionDouble(options, ConfigurationKeyword.GraphOffset, Identifier, false, DefaultValue),
                FileCollection.Create(server, config),
                WebLinkCollection.Create(server, config));
        }
    }
}