using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CookComputing.XmlRpc;
using System.Threading;
using System.Text.RegularExpressions;
using Microsoft.Phone.Shell;

namespace SvP_Mobile_Client
{
    public partial class viewMessage : PhoneApplicationPage
    {
        private string threadid = string.Empty;

        public viewMessage()
        {
            InitializeComponent();

            this.ReloadStrings();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            this.progress1.Visibility = System.Windows.Visibility.Visible;
            if (this.NavigationContext.QueryString.ContainsKey("threadid"))
            {
                this.threadid = this.NavigationContext.QueryString["threadid"];
            }

            this.GetThread(int.Parse(this.threadid), 0);
            base.OnNavigatedTo(e);
        }

        private void GetThread(int threadid, int offset = 0)
        {
            DrupalConnection.GetInstance().GetProxy().BeginPrivatemsgGetThread(threadid, offset, asr =>
            {
                Dispatcher.BeginInvoke(delegate()
                {
                    try
                    {
                        var getThreadResponse = DrupalConnection.GetInstance().GetProxy().EndPrivatemsgGetThread(asr);

                        if (getThreadResponse is XmlRpcStruct)
                        {
                            this.subject.Text = getThreadResponse["subject"].ToString();

                            int partCurr = 0;
                            int partCount = ((XmlRpcStruct)getThreadResponse["participants"]).Count;

                            this.participants.Text = AppResources.Participants;

                            foreach (System.Collections.DictionaryEntry participant in (XmlRpcStruct)getThreadResponse["participants"])
                            {
                                if (partCount == (partCurr + 1))
                                {
                                    this.participants.Text += ((XmlRpcStruct)participant.Value)["name"];
                                }
                                else
                                {
                                    this.participants.Text += ((XmlRpcStruct)participant.Value)["name"] + ", ";
                                }

                                partCurr++;
                            }

                            int mess = 0;
                            this.lstBody.Items.Clear();

                            foreach (XmlRpcStruct item in (XmlRpcStruct[])getThreadResponse["messages"])
                            {
                                PrivatemsgListboxBlock msgBlock = new PrivatemsgListboxBlock();
                                msgBlock.From = ((XmlRpcStruct)item["author"])["name"].ToString() + " " + utility.UnixTimeToDateTime(item["timestamp"].ToString());
                                msgBlock.Message = StripEndTagsRegex(item["body"].ToString());
                                msgBlock.Message = StripStartTagsRegex(msgBlock.Message);
                                
                                this.lstBody.Items.Add(msgBlock);
                            }
                        }
                        //textBlock1.Text = "Message1: " + ((CookComputing.XmlRpc.XmlRpcStruct[])getThreadResponse["messages"])[0]["body"].ToString() + "\r\n\r\n";
                        //textBlock1.Text = textBlock1.Text + "Message 2: " + ((CookComputing.XmlRpc.XmlRpcStruct[])getThreadResponse["messages"])[1]["body"].ToString() + "\r\n\r\n";
                        //textBlock1.Text = textBlock1.Text + "Message 3: " + ((CookComputing.XmlRpc.XmlRpcStruct[])getThreadResponse["messages"])[2]["body"].ToString() + "\r\n\r\n";
                        this.progress1.Visibility = System.Windows.Visibility.Collapsed;

                    }
                    catch (XmlRpcFaultException fex)
                    {
                        this.progress1.Visibility = System.Windows.Visibility.Collapsed;
                        //textBlock1.Text = fex.Message;
                    }
                    catch (Exception ex)
                    {
                        this.progress1.Visibility = System.Windows.Visibility.Collapsed;
                        //textBlock1.Text = ex.Message;
                    }
                });
            });
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void btnReply(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/replyMessage.xaml?threadid=" + threadid + "&subj=" + this.subject.Text, UriKind.Relative));

            /*
            PrivatemsgListboxBlock item1 = new PrivatemsgListboxBlock();
            item1.From = "Tibor";
            item1.Message = "Sprava";

            PrivatemsgListboxBlock item2 = new PrivatemsgListboxBlock();
            item2.From = "Igorik";
            item2.Message = "Sprava 2\r\nSprava 2\r\nSprava 2\r\nSprava 2\r\nSprava 2\r\nSprava 2\r\n";

            item1.Calculate();
            item2.Calculate();

            this.lstBody.Items.Add(item1);
            this.lstBody.Items.Add(item2);
            */
        }

        public static string StripStartTagsRegex(string source)
        {
            return Regex.Replace(source, "<.{1,3}>", string.Empty);
        }
        
        public static string StripEndTagsRegex(string source)
        {
            return Regex.Replace(source, "</.{1,3}>", "\r\n");
        }

        private void ReloadStrings()
        {
            ((ApplicationBarIconButton)this.ApplicationBar.Buttons[0]).Text = AppResources.appbarReply;

            subject.Text = AppResources.Subject;
            participants.Text = AppResources.Participants;
        }
    }

    public class PrivatemsgListboxBlock
    {
        public string From { get; set; }
        public string Message { get; set; }
        public double CalculateHeightBody { get; set; }
        public double CalculateHeightRectangle { get; set; }

    }
}