//
// HostPageConfiguration.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.Config.Graph;
using Ntp.Analyzer.Config.Navigation;
using Ntp.Analyzer.Config.Page.Collection;
using Ntp.Analyzer.Localize;
using Ntp.Config;

namespace Ntp.Analyzer.Config.Page
{
    /// <summary>
    /// Configuration for a HTML page showing status and graphs for an hosted NTP server.
    /// </summary>
    public sealed class HostPageConfiguration : PageConfigurationBase, ILinkable
    {
        private HostPageConfiguration(
            HostConfiguration server,
            string configName,
            int indentLevel,
            int frequency,
            bool initialRun,
            bool fixedRun,
            bool showUtc,
            string theme,
            string title,
            bool poolMember,
            bool queryDirect,
            PeerPageConfiguration peerPage,
            IEnumerable<GraphSetConfiguration> graphs,
            SummaryCollection summaries,
            FileCollection destinations,
            string link)
            : base(
                server,
                configName,
                indentLevel,
                frequency,
                initialRun,
                fixedRun,
                theme,
                title,
                destinations,
                link)
        {
            this.poolMember = poolMember;
            this.queryDirect = queryDirect;
            this.showUtc = showUtc;
            this.peerPage = peerPage;
            this.graphs = new List<GraphSetConfiguration>(graphs);
            this.summaries = summaries;
            graphPages = new List<HostGraphPageConfiguration>();
        }

        public const string Identifier = ConfigurationKeyword.HostPage;
        private new const bool DefaultInitialRun = true;
        private new const bool DefaultFixedRun = true;
        private const int DefaultFrequency = 5;
        private const bool DefaultShowUtc = false;
        private const bool DefaultPoolMember = false;
        private const bool DefaultQueryDirect = false;

        /// <summary>
        /// The parameters used in configuration files.
        /// </summary>
        private static readonly String[] Params =
        {
            ConfigurationKeyword.HostPage,
            ConfigurationKeyword.Frequency,
            ConfigurationKeyword.InitialRun,
            ConfigurationKeyword.FixedRun,
            ConfigurationKeyword.PageShowUtc,
            ConfigurationKeyword.PageTemplate,
            ConfigurationKeyword.PageTitle,
            ConfigurationKeyword.HostPagePoolMember,
            ConfigurationKeyword.HostPageQueryDirect,
            PeerPageConfiguration.Identifier,
            GraphSetConfiguration.Identifier,
            SummaryCollection.Identifier,
            FileCollection.Identifier,
            ConfigurationKeyword.PageLink
        };

        private readonly List<HostGraphPageConfiguration> graphPages;
        private readonly List<GraphSetConfiguration> graphs;
        private readonly PeerPageConfiguration peerPage;
        private readonly bool poolMember;
        private readonly bool queryDirect;
        private readonly bool showUtc;
        private readonly SummaryCollection summaries;

        /// <summary>
        /// Gets a value indicating whether there should be shown a link to pool.ntp.org.
        /// </summary>
        /// <value>
        /// <c>true</c> if pool member; otherwise, <c>false</c>.
        /// </value>
        public bool PoolMember
        {
            get { return poolMember; }
        }

        /// <summary>
        /// Gets a value indicating whether the NTP deamon should be directly quried.
        /// </summary>
        /// <value>
        /// <c>true</c> if directly quried; otherwise, <c>false</c>.
        /// </value>
        public bool QueryDirect
        {
            get { return queryDirect; }
        }

        /// <summary>
        /// Gets a value indicating whether time should be shown using UTC.
        /// </summary>
        /// <value>
        /// <c>true</c> if time should be shown using UTC; otherwise, <c>false</c>.
        /// </value>
        public bool ShowUtc
        {
            get { return showUtc; }
        }

        /// <summary>
        /// Gets the peer pages linked to this page.
        /// </summary>
        /// <value>The peer page.</value>
        public PeerPageConfiguration PeerPage
        {
            get { return peerPage; }
        }

        /// <summary>
        /// Gets the graphs to be displayed on this page.
        /// </summary>
        /// <value>The host graphs.</value>
        public IEnumerable<GraphSetConfiguration> Graphs
        {
            get { return graphs; }
        }

        /// <summary>
        /// Gets the peer summeries to be linked from this page.
        /// </summary>
        /// <value>The peer summeries.</value>
        public SummaryCollection PeerSummaries
        {
            get { return summaries; }
        }

        /// <summary>
        /// Gets the host graph pages to be linked from this page.
        /// </summary>
        /// <value>The host graph pages.</value>
        public IEnumerable<HostGraphPageConfiguration> GraphPages
        {
            get { return graphPages; }
        }

        /// <summary>
        /// Gets the values of settings in this configuration.
        /// </summary>
        /// <value>The items.</value>
        protected override IEnumerable<Object> Items
        {
            get
            {
                var items = new List<object> {ConfigName};

                if (ShowDefault || (!ShowDefault && Frequency != DefaultFrequency))
                    items.Add(Frequency);

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

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

                if (ShowDefault || (!ShowDefault && ShowUtc != DefaultShowUtc))
                    items.Add(ShowUtc);

                if (ShowDefault || (!ShowDefault && Theme.ToLower() != DefaultTheme.ToLower()))
                    items.Add(Theme);

                items.Add(Title);

                if (ShowDefault || (!ShowDefault && PoolMember != DefaultPoolMember))
                    items.Add(PoolMember);

                if (ShowDefault || (!ShowDefault && QueryDirect != DefaultQueryDirect))
                    items.Add(QueryDirect);

                if (PeerPage != null)
                    items.Add(PeerPage.ConfigName);

                items.Add(Graphs);

                if (PeerSummaries != null && PeerSummaries.Pages.Count() != 0)
                    items.Add(PeerSummaries);

                items.Add(Destinations);

                if (ShowDefault || (!ShowDefault && Link != DefaultLink))
                    items.Add(Link);

                return items.ToArray();
            }
        }

        /// <summary>
        /// Attachs the host graph pages to this page.
        /// </summary>
        /// <remarks>
        /// Only use from <see cref="HostGraphPageConfiguration" />
        /// </remarks>
        /// <param name="page">Page.</param>
        internal void AttachGraphPages(HostGraphPageConfiguration page)
        {
            graphPages.Add(page);
        }

        /// <summary>
        /// Returns a <see cref="System.String" /> that represents the current
        /// <see
        ///     cref="Ntp.Analyzer.Config.Page.HostPageConfiguration" />
        /// .
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents the current
        /// <see cref="Ntp.Analyzer.Config.Page.HostPageConfiguration" />.
        /// </returns>
        public override string ToString()
        {
            var list = new List<string> {ConfigurationKeyword.HostPage};

            if (ShowDefault || (!ShowDefault && Frequency != DefaultFrequency))
                list.Add(ConfigurationKeyword.Frequency);

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

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

            if (ShowDefault || (!ShowDefault && ShowUtc != DefaultShowUtc))
                list.Add(ConfigurationKeyword.PageShowUtc);

            if (ShowDefault || (!ShowDefault && Theme.ToLower() != DefaultTheme.ToLower()))
                list.Add(ConfigurationKeyword.PageTemplate);

            list.Add(ConfigurationKeyword.PageTitle);

            if (ShowDefault || (!ShowDefault && PoolMember != DefaultPoolMember))
                list.Add(ConfigurationKeyword.HostPagePoolMember);

            if (ShowDefault || (!ShowDefault && QueryDirect != DefaultQueryDirect))
                list.Add(ConfigurationKeyword.HostPageQueryDirect);

            if (PeerPage != null)
                list.Add(PeerPageConfiguration.Identifier);

            list.Add(GraphSetConfiguration.Identifier);

            if (PeerSummaries != null && PeerSummaries.Pages.Count() != 0)
                list.Add(SummaryCollection.Identifier);

            list.Add(FileCollection.Identifier);

            if (ShowDefault || (!ShowDefault && Link != DefaultLink))
                list.Add(ConfigurationKeyword.PageLink);

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

        /// <summary>
        /// Factory method.
        /// </summary>
        /// <param name="server">Server.</param>
        /// <param name="config">Config.</param>
        /// <param name="peerPages">Peer pages.</param>
        /// <param name="hostGraphs">Host graphs.</param>
        /// <param name="peerSummaries">Peer summaries.</param>
        public static HostPageConfiguration Create(
            HostConfiguration server,
            ConfigurationBlock config,
            IEnumerable<PeerPageConfiguration> peerPages,
            IEnumerable<GraphBaseConfiguration> hostGraphs,
            IEnumerable<PeerSummaryPageConfiguration> peerSummaries)
        {
            OptionSet options = GetOptions(Params, config);

            string peerPageName = GetOptionString(options, PeerPageConfiguration.Identifier, Identifier, false);
            PeerPageConfiguration peerPage = null;

            if (peerPageName != String.Empty)
            {
                peerPage = peerPages.SingleOrDefault(pp => pp.ConfigName == peerPageName);

                if (peerPage == null)
                {
                    ConfigError(String.Format(
                        ConfigurationMessage.MissingReference,
                        PeerPageConfiguration.Identifier, peerPageName, Identifier
                        ));

                    ConfigError(ConfigurationMessage.ConfiguredPeerPages);
                    foreach (PeerPageConfiguration peerPageConfig in peerPages)
                        ConfigError(peerPageConfig.ConfigName);
                }
            }

            return new HostPageConfiguration(
                server,
                GetOptionConfigName(options, ConfigurationKeyword.HostPage, Identifier, true),
                config.IndentLevel,
                GetOptionInteger(options, ConfigurationKeyword.Frequency, Identifier, false, DefaultFrequency),
                GetOptionBoolean(options, ConfigurationKeyword.InitialRun, Identifier, false, DefaultInitialRun),
                GetOptionBoolean(options, ConfigurationKeyword.FixedRun, Identifier, false, DefaultFixedRun),
                GetOptionBoolean(options, ConfigurationKeyword.PageShowUtc, Identifier, false, DefaultShowUtc),
                GetOptionString(options, ConfigurationKeyword.PageTemplate, Identifier, false, DefaultTheme),
                GetOptionString(options, ConfigurationKeyword.PageTitle, Identifier, false, String.Empty),
                GetOptionBoolean(options, ConfigurationKeyword.HostPagePoolMember, Identifier, false, DefaultPoolMember),
                GetOptionBoolean(options, ConfigurationKeyword.HostPageQueryDirect, Identifier, false,
                    DefaultQueryDirect),
                peerPage,
                GraphSetConfiguration.Create(server, hostGraphs, config, Identifier),
                SummaryCollection.Create(server, peerSummaries, config, Identifier),
                FileCollection.Create(server, config),
                GetOptionString(options, ConfigurationKeyword.PageLink, Identifier, false, null)
                );
        }
    }
}