using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

using BeWo.ServiceProxy;

using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;

using Microsoft.Win32;

namespace BeWo.View.Detail
{
    /// <summary>
    /// Interaction logic for HomeView.xaml
    /// </summary>
    public partial class SendMailView : BeWoView
    {
        // Dictionary<string, CompactEmployeeDC> _receiverMap = new Dictionary<string, CompactEmployeeDC>();
        private readonly List<CompactEmployeeDC> _receiverList = new List<CompactEmployeeDC>();

        private Upload _currentUpload = new Upload();

        public SendMailView()
        {
            this.InitializeComponent();
        }

        public SendMailView(Mode mode, MailDC mail)
            : this()
        {
            switch (mode)
            {
                case Mode.Forward:
                    this.FillForward(mail);
                    break;
                case Mode.Reply:
                    this.FillReply(mail);
                    break;
                default:
                    break;
            }
        }

        public enum Mode
        {
            Forward, 
            Reply
        }

        public override bool IsDirty
        {
            get
            {
                return !string.IsNullOrEmpty(this.mailTextBox.Text) && this.receiverWrapPanel.Children.Count > 0; // !string.IsNullOrEmpty(receiverTextBox.Text);
            }
        }

        protected override void Save()
        {
            var priority = this.lowPriorityRadioButton.IsChecked ?? false ? Priority.low : this.highPriorityRadioButton.IsChecked ?? false ? Priority.high : Priority.normal;

            var receiver = this.ParseReceiver();
            if (receiver == null)
            {
                return;
            }

            var mail = new MailDC { Subject = this.subjectTextBox.Text, Message = this.mailTextBox.Text, Priority = priority, Receiver = receiver, Sender = BeWoApp.LoggedOnUser.Employee.EmployeeOid, Status = Status.unread, SenderName = BeWoApp.LoggedOnUser.Employee.FirstName + " " + BeWoApp.LoggedOnUser.Employee.LastName };

            ServiceFacade.DoMailServiceAsync(
                // s => s.SendMail(mail)
                delegate(IMailService s)
                    {
                        var oid = s.SendMail(mail);
                        var tid = TableID.Mail;
                        foreach (Upload item in this.attachmentList.Items)
                        {
                            var progressStream = new ProgressStream(item.Dialog.OpenFile());
                            var package = new UploadPackage(null, 0, item.Dialog.SafeFileName, item.Description, oid, (int)tid, progressStream);

                            ServiceFacade.DoStreamingServiceAsync(service => service.UploadDocument(package));
                        }
                    });

            this.MainControl.NavigateTo(new HomeDragPanelView());
        }

        // private List<MailReceiverDC> ParseReceiver()
        // {
        // var result = new List<MailReceiverDC>();

        // var splitted = receiverTextBox.Text.Split(';');

        // foreach (var item in splitted)
        // {
        // //if (item.Contains('@'))
        // //{
        // //    result.Add(new MailReceiverDC() { EmailAddress = item });

        // //}
        // //else
        // //{
        // if (!_receiverMap.ContainsKey(item))
        // {
        // MessageBox.Show("Sie versuchen eine Mail an einen unbekannten Empfänger (" + item + ") zu versenden.\nVerwenden Sie bitte den Hinzufügen-Knopf statt den Namen händisch einzutippen.");
        // return null;
        // }
        // var empolyee = _receiverMap[item];

        // result.Add(new MailReceiverDC()
        // {
        // EmployeeOid = empolyee.EmployeeOid,
        // FirstName = empolyee.FirstName,
        // LastName = empolyee.LastName
        // });

        // //}
        // }
        // return result;
        // }
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            this.popup_employee.IsOpen = true;
        }

        private void AddReceiver(CompactEmployeeDC employee)
        {
            this._receiverList.Add(employee);

            var receiverButton = new Button { Content = employee.ToString(), Tag = employee, Margin = new Thickness(0, 0, 10, 0) };

            receiverButton.Click += this.receiverButton_Click;

            this.receiverWrapPanel.Children.Add(receiverButton);
        }

        private string ConvertToCitation(string text)
        {
            var result = new StringBuilder();
            using (var reader = new StringReader(text))
            {
                while (reader.Peek() >= 0)
                {
                    result.Append("> ");
                    result.AppendLine(reader.ReadLine());
                }
            }

            return result.ToString();
        }

        private void EmployeeSearchView_EmployeeSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            this.popup_employee.IsOpen = false;

            // if (_receiverMap.ContainsKey(e.Data.ToString()))
            if (this._receiverList.Contains(e.Data))
            {
                MessageBox.Show("Empfänger wurde bereits hinzugefügt");
                return;
            }

            // _receiverMap.Add(e.Data.ToString(), e.Data);
            var employee = e.Data;

            this.AddReceiver(employee);

            // if (!string.IsNullOrEmpty(receiverTextBox.Text))
            // receiverTextBox.Text += "; ";

            // receiverTextBox.Text += e.Data.ToString();
        }

        private void FillForward(MailDC mail)
        {
            this.subjectTextBox.Text = "WD: " + mail.Subject;
            this.mailTextBox.Text = mail.Message;
        }

        private void FillReply(MailDC mail)
        {
            this.subjectTextBox.Text = "AW: " + mail.Subject;
            this.mailTextBox.Text = this.ConvertToCitation(mail.Message);

            // ServiceFacade.DoEmployeeServiceAsync(s => s.LoadEmployee(mail.Sender.Value));
            ServiceFacade.DoEmployeeServiceAsync(s => this.Dispatcher.BeginInvoke((Action)delegate { this.AddReceiver(s.GetAllActiveEmployeesCompact().Where(e => e.EmployeeOid == mail.Sender.Value).First()); }));
        }

        private List<MailReceiverDC> ParseReceiver()
        {
            var result = new List<MailReceiverDC>();
            foreach (var empolyee in this._receiverList)
            {
                result.Add(new MailReceiverDC { EmployeeOid = empolyee.EmployeeOid, FirstName = empolyee.FirstName, LastName = empolyee.LastName });
            }

            return result;
        }

        private void button_removeAttachment_Click(object sender, RoutedEventArgs pe)
        {
            this.attachmentList.Items.Remove(this.attachmentList.SelectedItem);
        }

        private void button_uploadDocument_Click(object sender, RoutedEventArgs pe)
        {
            this._currentUpload.Description = this.fileNoticeTextbox.Text;
            this.attachmentList.Items.Add(this._currentUpload);

            this._currentUpload = new Upload();

            this.fileNoticeTextbox.Text = string.Empty;
            this.popupedit_file.Text = string.Empty;

            // var lUlPackage = new UploadPackage(popupedit_file.Text, textbox_fileNotice.Text, _ObjectOid, (int)_ObjectTid, _Upload);

            // ServiceFacade.DoStreamingServiceAsync(s => s.UploadDocument(lUlPackage),
            // r => this.Dispatch(delegate
            // {
            // _List.Add(r.Attachment);
            // progressbar_upload.Value = 0;
            // text_progress.Content = string.Empty;
            // _Upload = null;
            // button_uploadDocument.IsEnabled = false;
            // popupedit_file.Text = string.Empty;
            // }));
        }

        private void popupedit_file_PopUpClick(object sender, RoutedEventArgs ev)
        {
            var dialog = new OpenFileDialog();

            if (dialog.ShowDialog() == true)
            {
                // _Upload = new ProgressStream(dialog.OpenFile());
                // popupedit_file.Text = dialog.SafeFileName;
                // button_uploadDocument.IsEnabled = true;

                // _Upload.ProgressChanged += (s, e) =>
                // {
                // Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                // (Action)delegate
                // {
                // progressbar_upload.Value = e.Data;
                // text_progress.Content = string.Format("Bitte warten... {0:00}%", e.Data * 100);
                // });
                // };
                this._currentUpload.Dialog = dialog;
                this.popupedit_file.Text = dialog.SafeFileName;
            }
        }

        private void receiverButton_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            var receiver = button.Tag as CompactEmployeeDC;

            this._receiverList.Remove(receiver);
            this.receiverWrapPanel.Children.Remove(button);
        }

        private class Upload
        {
            public string Description { get; set; }

            public OpenFileDialog Dialog { get; set; }

            public override string ToString()
            {
                return this.Description + " (" + this.Dialog.SafeFileName + ")";
            }
        }
    }
}