namespace Lauener.Core.Phone.Azure
{
    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Xml.Linq;

    using Lauener.Core.Azure;
    using Lauener.Core.Logger;

    internal class AzureNotificationService<TName> : IAzureNotificationService<TName>
    {
        private readonly ILogger logger;

        private readonly ISasTokenHelper sasTokenHelper;

        private string baseAddress;

        private string fullAddress;

        private string sharedAccessKeyName;

        private string sharedAccessKeyValue;

        public AzureNotificationService(ILogger logger, ISasTokenHelper sasTokenHelper, IAzureConnectionString<TName> connectionString)
        {
            this.logger = logger;
            this.sasTokenHelper = sasTokenHelper;
            var tempString = connectionString.GetConnectionString();
            if (tempString == null)
            {
                throw new ArgumentNullException("connectionString");
            }

            var temp = tempString.Split(';');
            this.baseAddress = "https://" + temp[0].Split('=')[1].Replace("sb://", string.Empty).Replace("/", string.Empty);
            this.fullAddress = string.Format("{0}/{1}", this.baseAddress, connectionString.GetName());
            this.sharedAccessKeyName = temp[1].Split('=')[1];
            this.sharedAccessKeyValue = temp[2].Replace(temp[2].Split('=')[0] + "=", string.Empty);
        }

        public void SendNotification(string message)
        {
            var xml = @"<toast><visual><binding template=""ToastText01""><text id=""1"">"+message+"</text></binding></visual></toast>";
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();

                var token = this.sasTokenHelper.Create(this.fullAddress, this.sharedAccessKeyName, this.sharedAccessKeyValue);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", token);


                HttpContent content = new StringContent(xml, Encoding.UTF8);
                content.Headers.Add("ContentType", "application/json;charset=utf-8");
                content.Headers.Add("ServiceBusNotification-Format", "windows");
                //ServiceBusNotification-Tags
                content.Headers.Add("X-WNS-Type", "wns/toast");

                //content.Headers.Add("Priority", "High");
                //content.Headers.Add("Customer", "12345");

                this.logger.Debug("Send Notification " + xml);
                var response = client.PostAsync(this.fullAddress + "/messages" + "?api-version=2013-08 ", content).Result;
                if (response.IsSuccessStatusCode)
                {
                }
                else
                {
                    this.logger.Error("Message " + response.StatusCode);
                }
            }
        }

        public void RegisterForNotification()
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();

                var token = this.sasTokenHelper.Create(this.fullAddress, this.sharedAccessKeyName, this.sharedAccessKeyValue);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", token);

                var xml = new StringBuilder();
                xml.Append(@"<?xml version=""1.0"" encoding=""utf-8""?>");
                xml.Append(@"<entry xmlns=""http://www.w3.org/2005/Atom"">");
                xml.Append(@"    <content type=""application/xml"">");
                xml.Append(@"        <WindowsRegistrationDescription xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"">");
                //xml.Append(@"            <Tags>myTag, myOtherTag</Tags>");
                xml.Append(@"            <ChannelUri>"+this.fullAddress+"</ChannelUri>");
                xml.Append(@"        </WindowsRegistrationDescription>");
                xml.Append(@"    </content>");
                xml.Append(@"</entry>");

                var test = XDocument.Parse(xml.ToString()).ToString();

                HttpContent content = new StringContent(xml.ToString(), Encoding.UTF8);
                content.Headers.Add("ContentType", "application/atom+xml;type=entry;charset=utf-8");
                content.Headers.Add("x-ms-version", "2013-08");

                //content.Headers.Add("Priority", "High");
                //content.Headers.Add("Customer", "12345");

                this.logger.Debug("Send Notification " + xml);
                var response = client.PostAsync(this.fullAddress + "/registrations/?api-version=2013-08", content).Result;
                if (response.IsSuccessStatusCode)
                {
                }
                else
                {
                    this.logger.Error("Message " + response.StatusCode);
                }
            }
        }
    }
}