// 
// 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.Globalization;
using System.Net;
using System.Text;
using Ntp.Analyzer.Objects;
using Ntp.Common.Web;

namespace Ntp.Analyzer.Render.Peer
{
    public sealed class BootstrapPeerInfoRender : HtmlObjectRender
    {
        public BootstrapPeerInfoRender(
            Uri webPath,
            TimeServer server,
            DateTime now,
            DateTime next,
            string name,
            string ip)
            : base(webPath)
        {
            this.server = server;
            this.now = now;
            this.next = next;
            this.name = name;
            this.ip = ip;
        }

        private readonly string ip;
        private readonly string name;
        private readonly DateTime next;
        private readonly DateTime now;
        private readonly TimeServer server;

        private string Name => string.IsNullOrEmpty(server?.Name) ? name : server.Name;

        private string StratumText
        {
            get
            {
                if (server == null || server.Stratum == 0)
                    return null;

                switch (server.Stratum)
                {
                    case 1:
                        return "one";
                    case 2:
                        return "two";
                    case 3:
                        return "three";
                    case 4:
                        return "four";
                    case 5:
                        return "five";
                    case 6:
                        return "six";
                    case 7:
                        return "seven";
                    default:
                        return null;
                }
            }
        }

        public string Time => string.Concat(
            now.ToLongDateString(),
            " ",
            TimeZoneInfo.Local.IsDaylightSavingTime(now)
                ? TimeZoneInfo.Local.DaylightName
                : TimeZoneInfo.Local.StandardName,
            " ",
            now.ToLongTimeString()
            );

        public string Location => string.IsNullOrEmpty(server?.Location) ? PageText.HtmlBlank : server.Location;

        private string ServerSync => string.IsNullOrEmpty(server?.Server) ? PageText.HtmlBlank : server.Server;

        private string IpV4Address
        {
            get
            {
                if (server?.Address == null || Equals(server.Address, IPAddress.None))
                    return PageText.HtmlBlank;

                return server.Address.ToString();
            }
        }

        private string ServerAccess
        {
            get
            {
                if (string.IsNullOrEmpty(server?.AccessPolicy))
                    return PageText.HtmlBlank;

                switch (server.AccessPolicy)
                {
                    case "OpenAccess":
                        return "Open access";
                    default:
                        return "Unknown";
                }
            }
        }

        private string IpV6Address => string.IsNullOrEmpty(server?.V6Address) ? PageText.HtmlBlank : server.V6Address;

        private string ServiceArea
        {
            get
            {
                if (string.IsNullOrEmpty(server?.ServiceArea))
                    return PageText.HtmlBlank;

                string description = server.ServiceArea.Trim();
                string firstLetter = description.Substring(0, 1);
                string rest = description.Substring(1);

                return firstLetter.ToUpper() + rest;
            }
        }

        private string PoolMemberStatus
        {
            get
            {
                if (server == null)
                    return PageText.HtmlBlank;

                return server.IsPoolMember
                    ? "Server is pool member"
                    : "Server is not a pool member";
            }
        }

        private string PoolMemberLink
        {
            get
            {
                if (server == null || !server.IsPoolMember)
                    return null;

                string address =
                    server.Address == null || Equals(server.Address, IPAddress.None)
                        ? ip
                        : server.Address.ToString();

                var builder = new StringBuilder();
                builder.Append(@"<a class=""btn btn-lg btn-primary"" href=""");
                builder.Append("http://www.pool.ntp.org/scores/");
                builder.Append(address);
                builder.Append(@""">View info on pool.ntp.org &raquo;</a>");
                return builder.ToString();
            }
        }

        private string ProviderLink
        {
            get
            {
                if (string.IsNullOrEmpty(server?.ProviderPage))
                    return null;

                var builder = new StringBuilder();
                builder.Append(@"<a class=""btn btn-lg btn-primary"" href=""");
                builder.Append(server.ProviderUrl);
                builder.Append(@""">View info on ");
                builder.Append(server.ProviderPage);
                builder.Append("  &raquo;</a>");
                return builder.ToString();
            }
        }

        public override string Render()
        {
            var builder = new StringBuilder();

            builder.AppendLine(@"      <div class=""row"">");
            builder.AppendLine(@"        <div class=""col-md-2""><b>Server location</b></div>");
            builder.Append(@"        <div class=""col-md-10"">");
            builder.Append(Location);
            builder.AppendLine("</div>");
            builder.AppendLine(@"      </div>");

            builder.AppendLine(@"      <div class=""row"">");
            builder.AppendLine(@"        <div class=""col-md-2""><b>Synchronization</b></div>");
            builder.Append(@"        <div class=""col-md-10"">");
            builder.Append(ServerSync);
            builder.AppendLine("</div>");
            builder.AppendLine(@"      </div>");

            builder.AppendLine(@"      <div class=""row"">");
            builder.AppendLine(@"        <div class=""col-md-2""><b>IP address</b></div>");
            builder.Append(@"        <div class=""col-md-4"">");
            builder.Append(IpV4Address);
            builder.AppendLine("</div>");

            builder.AppendLine(@"        <div class=""col-md-2""><b>Access policy</b></div>");
            builder.Append(@"        <div class=""col-md-4"">");
            builder.Append(ServerAccess);
            builder.AppendLine("</div>");
            builder.AppendLine(@"      </div>");

            builder.AppendLine(@"      <div class=""row"">");
            builder.AppendLine(@"        <div class=""col-md-2""><b>IPv6 address</b></div>");
            builder.Append(@"        <div class=""col-md-4"">");
            builder.Append(IpV6Address);
            builder.AppendLine(@"</div>");

            builder.AppendLine(@"        <div class=""col-md-2""><b>Service area</b></div>");
            builder.Append(@"        <div class=""col-md-4"">");
            builder.Append(ServiceArea);
            builder.AppendLine(@"</div>");
            builder.AppendLine(@"      </div>");

            builder.AppendLine(@"      <div class=""row"">");
            builder.AppendLine(@"        <div class=""col-md-2""><b>Pool member</b></div>");
            builder.Append(@"        <div class=""col-md-4"">");
            builder.Append(PoolMemberStatus);
            builder.AppendLine(@"</div>");

            builder.AppendLine(@"        <div class=""col-md-2""><b>Description</b></div>");
            builder.Append(@"        <div class=""col-md-4"">");
            builder.Append(server?.Updated.ToLongDateString() ?? PageText.HtmlBlank);
            builder.AppendLine(@"</div>");
            builder.AppendLine(@"      </div>");

            builder.AppendLine(@"      <p class=""pool"">");

            if (PoolMemberLink != null)
            {
                builder.Append(@"        ");
                builder.Append(PoolMemberLink);
                builder.AppendLine(@"&nbsp;&nbsp;&nbsp;");
            }

            if (ProviderLink != null)
            {
                builder.Append(@"        ");
                builder.Append(ProviderLink);
                builder.AppendLine(@"&nbsp;&nbsp;&nbsp;");
            }

            if (server != null && server.Id <= 10000)
            {
                builder.Append(@"        ");
                builder.Append(
                    @"<a class=""btn btn-lg btn-primary"" href=""http://support.ntp.org/bin/view/Servers/PublicTimeServer");
                builder.Append(server.Id.ToString(CultureInfo.InvariantCulture).PadLeft(6, '0'));
                builder.AppendLine(@""">View info on support.ntp.org &raquo;</a>");
            }

            builder.AppendLine(@"      </p>");

            return builder.ToString();
        }

        public override string RenderFooter()
        {
            var builder = new StringBuilder();

            builder.AppendLine("    </div>");
            builder.AppendLine("  </div>");

            return builder.ToString();
        }

        public override string RenderHead()
        {
            var builder = new StringBuilder();

            builder.AppendLine(@"  <div class=""container"">");
            builder.AppendLine(@"    <div class=""jumbotron"">");

            builder.Append("      <h1>");
            builder.Append(Name);
            builder.Append("</h1>");

            if (StratumText != null)
            {
                builder.Append("&nbsp;&nbsp;&nbsp;&nbsp;<h3>Stratum ");
                builder.Append(StratumText);
                builder.AppendLine(" server</h3>");
            }

            builder.Append("      <p>");
            builder.Append(Time);
            builder.Append(". ");
            builder.Append("Next refresh scheduled at ");
            builder.Append(next.ToShortTimeString());
            builder.AppendLine(".</p>");

            return builder.ToString();
        }
    }
}