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

using BS.Shared.Core;
using BS.Shared.Extensions;

namespace BeWo.View
{
    /// <summary>
    /// Interaction logic for YearMonthFilter.xaml
    /// </summary>
    public partial class YearMonthFilter : UserControl
    {
        public YearMonthFilter()
        {
            this.InitializeComponent();
            this.InitDateCombos();

            this.combobox_month.SelectionChanged += (s, e) => this.FireFilterSpanChanged();
            this.combobox_year.SelectionChanged += (s, e) => this.FireFilterSpanChanged();
            this.combobox_month.IsEnabledChanged += (s, e) => this.FireFilterSpanChanged();
            this.combobox_year.IsEnabledChanged += (s, e) => this.FireFilterSpanChanged();
        }

        public event EventHandler<EventArgs<DateTimeSpan>> FilterSpanChanged;

        public DateTimeSpan FilterSpan
        {
            get
            {
                if (!this.checkbox_yearfilter.IsChecked.Value)
                {
                    return null;
                }

                var lResult = new DateTimeSpan();
                if (this.checkbox_monthfilter.IsChecked.Value)
                {
                    lResult.StartDateTime = new DateTime((int)this.combobox_year.SelectedItem, DateTimeFormatInfo.CurrentInfo.MonthNames.IndexOf((string)this.combobox_month.SelectedItem) + 1, 1);
                    lResult.EndDateTime = lResult.StartDateTime.AddMonths(1);
                }
                else
                {
                    lResult.StartDateTime = new DateTime((int)this.combobox_year.SelectedItem, 1, 1);
                    lResult.EndDateTime = lResult.StartDateTime.AddYears(1);
                }

                lResult.EndDateTime = lResult.EndDateTime.AddSeconds(-1);
                return lResult;
            }
        }

        private void FireFilterSpanChanged()
        {
            if (this.FilterSpanChanged != null)
            {
                this.FilterSpanChanged(this, new EventArgs<DateTimeSpan>(this.FilterSpan));
            }
        }

        private void InitDateCombos()
        {
            this.combobox_month.ItemsSource = DateTimeFormatInfo.CurrentInfo.MonthNames.Where(s => !string.IsNullOrEmpty(s));
            this.combobox_month.SelectedIndex = DateTime.Now.Month - 1;

            var years = new List<int>();
            for (int i = 0; i <= 10; i++)
            {
                years.Add(DateTime.Now.Year - i);
            }

            this.combobox_year.ItemsSource = years;
            this.combobox_year.SelectedItem = DateTime.Now.Year;
        }
    }
}