using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using BeWo.Controls;
using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.ViewModel;

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

using DevExpress.Xpf.Core;
using DevExpress.Xpf.Printing;
using DevExpress.XtraReports.UI;

namespace BeWo.View.Detail.Report
{
    /// <summary>
    /// Interaction logic for ServicesReportView.xaml
    /// </summary>
    public partial class ServicesReportView : BeWoView
    {
        private CompactCustomerDC _Customer;

        private CompactEmployeeDC _Employee;

        private CompactOrganisationDC _Organisation;

        public CompactCustomerDC Customer { get { return _Customer; } set { _Customer = value; } }

        public CompactEmployeeDC Employee { get { return _Employee; } set { _Employee = value; } }

        public CompactOrganisationDC Organisation { get { return _Organisation; } set { _Organisation = value; } }

        public ServicesReportView()
        {
            InitializeComponent();
            InitDateCombos();
            InitServiceCategoryCombo();

			//if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View))
			//{
			//	checkbox_all.IsEnabled = false;
			//	checkbox_all.IsChecked = false;
			//}

            combobox_month.SelectionChanged += combobox_month_SelectionChanged;

			ThemeManager.SetTheme(BeWoApp.CurrentBeWo.MainWindow, Theme.Office2010Black);
            //ThemeManager.SetTheme(docPrevControl, Theme.Office2010Black);

            Unloaded += delegate { ThemeManager.SetTheme(BeWoApp.CurrentBeWo.MainWindow, null); docPrevControl.Visibility = Visibility.Collapsed; };
        }

        void combobox_month_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            InitDayCombos();
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (popupedit_customer == null)
                return;

            popupedit_customer.Text = string.Empty;
            _Customer = null;
        }

        private void CustomerSearchView_CustomerSelected(object sender, EventArgs<CompactCustomerDC> e)
        {
            _Customer = e.Data;
            popupedit_customer.Text = _Customer.ToString();
            popup_customer.IsOpen = false;
        }

        private void EmployeeSearchView_EmployeeSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            _Employee = e.Data;
            popupedit_employee.Text = _Employee.SimpleDescription;
            popup_employee.IsOpen = false;

        }

        private void InitServiceCategoryCombo()
        {
            ServiceFacade.DoOperationsServiceSync(s => ServiceCategoriesComboBox.ItemsSource = s.GetAllServiceCategories());
            ServiceCategoriesComboBox.SelectedIndex = -1;
        }

        private void InitDateCombos()
        {
            this.combobox_month.ItemsSource = DateTimeFormatInfo.CurrentInfo.MonthNames.Where(s => !string.IsNullOrEmpty(s));
            int monthIdx = DateTime.Now.Month - 1;
            //if (DateTime.Now.Day < 15)
            //{
                monthIdx--;
                if (monthIdx < 0)
                    monthIdx = 11;
            //}
            this.combobox_month.SelectedIndex = monthIdx;
            var years = new List<int>();
            for (int i = 0; i <= 10; i++)
            {
                years.Add(DateTime.Now.Year - i);
            }

            this.combobox_year.ItemsSource = years;
            if (monthIdx == 11)
            {
                this.combobox_year.SelectedItem = DateTime.Now.Year - 1;
            }
            else
                this.combobox_year.SelectedItem = DateTime.Now.Year;

            InitDayCombos();
        }

        private void InitDayCombos()
        {
            int year = DateTime.Now.Year;

            var yearObj = this.combobox_year.SelectedItem;
            if (yearObj != null)
                year = Int32.Parse(yearObj.ToString());

            int month = this.combobox_month.SelectedIndex + 1;

            int lastStartIndex = combobox_Startday.SelectedIndex;
            //if (combobox_Startday.HasItems)
            //    combobox_Startday.Items.Clear();
            int lastEndIndex = combobox_Endday.SelectedIndex;
            //if (combobox_Endday.HasItems)
            //    combobox_Endday.Items.Clear();

            int days = DateTime.DaysInMonth(year, month);
            List<int> dayList = new List<int>();
            for (int i = 1 ; i <= days; i++)
            {
                dayList.Add(i);
            }


            this.combobox_Startday.ItemsSource = dayList;
            if (lastStartIndex >= dayList.Count)
                lastStartIndex = dayList.Count - 1;
            if (lastStartIndex < 0)
                lastStartIndex = 0;
            this.combobox_Startday.SelectedIndex = lastStartIndex;

            this.combobox_Endday.ItemsSource = dayList;
            if (lastEndIndex >= 27)
                lastEndIndex = dayList.Count - 1;
            if (lastEndIndex < 0)
                lastEndIndex = dayList.Count - 1;
            this.combobox_Endday.SelectedIndex = lastEndIndex;
        }

        private void OrganisationSearchView_OrganisationSelected(object sender, EventArgs<CompactOrganisationDC> e)
        {
            _Organisation = e.Data;
            popupedit_costbearer.Text = _Organisation.Name;
            popup_costbearer.IsOpen = false;
        }

        private void button_generate_Click(object sender, RoutedEventArgs e)
        {
            long orgaOid = 0;
            long empOid = 0;
            if (checkbox_all.IsChecked.Value)
                _Customer = null;

            if (!chkForAllCostbearer.IsChecked.Value)
                _Organisation = null;

            if (!chkForAllEmployees.IsChecked.Value)
                _Employee = null;

            if (!checkbox_all.IsChecked.Value && _Customer == null)
                MessageBox.Show("Bitte wählen Sie einen Klienten aus.", "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Information);
            else if (chkForAllCostbearer.IsChecked.Value && _Organisation == null)
                MessageBox.Show("Bitte wählen Sie einen Kostenträger aus.", "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Information);
            else if (chkForAllEmployees.IsChecked.Value && _Employee == null)
                MessageBox.Show("Bitte wählen Sie eine/n Mitarbeiter/in aus.", "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Information);
            else if (ChkForAllServiceCategories.IsChecked.HasValue && ChkForAllServiceCategories.IsChecked.Value && ServiceCategoriesComboBox.SelectedItem == null)
                 MessageBox.Show("Bitte wählen Sie eine Leistungskategorie aus.", "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Information);
            else
            {
                if (_Organisation != null)
                    orgaOid = _Organisation.OrganisationOid;

                if (_Employee != null)
                    empOid = _Employee.EmployeeOid;

                string url = BeWoApp.SiteOfOrigin + "/ReportView.aspx?";
                if (_Customer != null)
                    url += "cOid=" + Customer.CustomerOid + "&type=" + Utils.EnumName(ReportTypes.ServiceOverviewSingleCustomer);
                else
                    url += "type=" + Utils.EnumName(ReportTypes.ServiceOverviewAllCustomers);

                url += "&orgaOid=" + orgaOid + "&empOid=" + empOid + "&month=" + (combobox_month.SelectedIndex + 1) +
                       "&year=" + combobox_year.SelectedItem + "&start=" + combobox_Startday.SelectedItem + "&end=" +
                       combobox_Endday.SelectedItem;

                if (ChkForAllServiceCategories.IsChecked.HasValue && ChkForAllServiceCategories.IsChecked.Value)
                {
                    url += "&scOid=" + ((ServiceCategoryDC)ServiceCategoriesComboBox.SelectedItem).ServiceCategoryOid;
                }

                //var tempToken = string.Empty;
                //ServiceFacade.DoDownloadServiceSync(s => tempToken = s.CreateTemporaryToken(url, true));
                //string addChar = (url.Contains("?")) ? "&" : "?";
                //url = url + addChar + "token=" + tempToken;

                url = BeWoWpfUtils.GetHTMLEncodedURL(url);

				BeWoUtils.NavigateToReportUri(url, "Quittierungsbeleg", docPrevControl);

            }
        }

        private void listbox_month_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.combobox_month.IsEnabled = false;
        }

        private void listbox_year_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.combobox_year.IsEnabled = false;
        }

        private void popupedit_costbearer_PopUpClick(object sender, RoutedEventArgs e)
        {
            popup_costbearer.IsOpen = true;
        }

        private void popupedit_customer_PopUpClick(object sender, RoutedEventArgs e)
        {
            popup_customer.IsOpen = true;
        }

        private void popupedit_employee_PopUpClick(object sender, RoutedEventArgs e)
        {
            popup_employee.IsOpen = true;
        }

        private void Popupedit_customer_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || _Customer == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View))
                return;

            VMFactory.CreateCustomerVMAsync(_Customer.CustomerOid, cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<CustomerVM, CustomerDC, ServicesReportView>(cb, this, () => this.Dispatch(
                () => BeWoUtils.UpdateAllViews(_Customer)))));
        }

        private void Popupedit_costbearer_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || _Organisation == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.OrganisationView_View))
                return;

            VMFactory.CreateOrganisationVMAsync(_Organisation.OrganisationOid, cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<OrganisationVM, OrganisationDC, ServicesReportView>(cb, this, () => this.Dispatch(
                () => BeWoUtils.UpdateAllViews(_Organisation)))));
        }

        private void Popupedit_employee_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || _Employee == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
                return;

            VMFactory.CreateEmployeeVMAsync(_Employee.EmployeeOid, cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, ServicesReportView>(cb, this, () => this.Dispatch(
                () => BeWoUtils.UpdateAllViews(_Employee)))));
        }
    }
}