using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
//using WcfServiceReceiveNotificationURL;
using System.ServiceModel;
using System.ServiceModel.Description;



namespace WP7PushNotification
{

	public partial class MainForm : Form
	{
        ServiceHost host;
        //Hier eine gültige URL angeben, wo der WCF Dienst erreicht werden soll.
        //Der Port muss dabei noch verfügbar sein
        //127.0.0.1 und localhost sind keine gültigen Adressen
        Uri baseAddress = new Uri("http://192.168.179.20:8080/ReceiveNotificationURLService");

        public MainForm()
        {
            InitializeComponent();

            //Erstelle WCF Dienst und registriere Methode für das NotificationURLChanged-Ereignis
            ReceiveNotificationURLService service = new ReceiveNotificationURLService();
            service.NotificationURLChanged += new NotificationURLChangedEventHandler(service_NotificationURLChanged);
            host = new ServiceHost(service, baseAddress);
            //Starten des WCF Dienstes
            host.Open();
            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
        }

        void service_NotificationURLChanged(object sender, URLChangedEventArgs e)
        {
            //Ereignisbehandlung für das WCF Ereignis, wenn eine neue URL empfangen wurde
            URITextBox.Text = e.NewURL;
        }

        void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //WCF Dienst beim Beenden schliessen
            host.Close();
        }

        #region Schaltflächen Ereignisbehandlung
        private void btnSendToast_Click(object sender, EventArgs e)
		{
			try
			{
                SendToastNotification(txtSender.Text, txtMessage.Text);	
			}
			catch (Exception ex)
			{
			}
		}

        private void btnUpdateTile_Click(object sender, EventArgs e)
        {

            try
            {
                SendTileNotification(txtUrl.Text, txtMessage.Text, Convert.ToInt32(nudTileNumber.Value));
            }
            catch (Exception ex)
            {
            }
        }

        private void btnSendRAWData_Click(object sender, EventArgs e)
        {
            SendRAWDataNotification();
        }
        #endregion

        private void SendToastNotification(String sender, String msg)
        {
            string data = string.Format(
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<wp:Notification xmlns:wp=\"WPNotification\">" +
                    "<wp:Toast>" +
                        "<wp:Text1>{0}</wp:Text1>" +
                        "<wp:Text2>{1}</wp:Text2>" +
                    "</wp:Toast>" +
                "</wp:Notification>",
                sender, msg);

            WebHeaderCollection header = new WebHeaderCollection();
            header.Add("X-WindowsPhone-Target", "toast");
            header.Add("X-NotificationClass", "2");

            PostUrl(URITextBox.Text, header, data);
        }

        private void SendTileNotification(String url, String msg, int count)
        {
            string data =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
     "<wp:Tile>" +
                "<wp:BackgroundImage>"+url+"</wp:BackgroundImage>" +
            "<wp:Count>"+count+"</wp:Count>" +
            "<wp:Title>" + msg + "</wp:Title>" +
     "</wp:Tile>" +
"</wp:Notification>";

            WebHeaderCollection header = new WebHeaderCollection();
            header.Add("X-WindowsPhone-Target", "token");
            header.Add("X-NotificationClass", "1");

            PostUrl(URITextBox.Text, header, data);
        }
        
        private void SendRAWDataNotification()
        {
            string data = @"<?xml version='1.0'?>
<catalog>
   <book id='bk101'>
      <author>Gambardella, Matthew</author>
   </book>
</catalog>
";

            WebHeaderCollection header = new WebHeaderCollection();
            header.Add("X-NotificationClass", "3");

            PostUrl(URITextBox.Text, header, data);
        }

        //Helfermethode zum Senden der Benachrichtigung
        protected void PostUrl(string url, WebHeaderCollection headers, string data)
        {
            //Erstellen eines neuen Webrequest mit der vom Gerät empfangenen Adresse
            WebRequest request = WebRequest.Create(url);

            //Es werden Benachrichtigungen immer nur im XML Format versand
            request.ContentType = "text/xml";
            request.Method = "POST";

            if (headers != null)
                request.Headers = headers;
            
            //Schreiben der Nachricht in den Request-Stream
            byte[] bytes = Encoding.UTF8.GetBytes(data);

            request.ContentLength = bytes.Length;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);

                try
                {
                    //Auslesen des Antwortstatus
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    string notificationStatus = response.Headers["X-NotificationStatus"];
                    string subscriptionStatus = response.Headers["X-SubscriptionStatus"];
                    string connectionStatus = response.Headers["X-DeviceConnectionStatus"];

                    MessageBox.Show(String.Format("X-NotificationStatus:{0}\r\nX-SubscriptionStatus:{1}\r\nX-DeviceConnectionStatus:{2}", notificationStatus, subscriptionStatus, connectionStatus));
                }
                catch (WebException ex)
                {
                    MessageBox.Show("WebException occured with Statuscode:" + ((HttpWebResponse)ex.Response).StatusCode.ToString());
                }
            }
        }
    }

}
