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 HolidayManager.Db;

namespace HolidayManager
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        // 페이지를 방문할 때,
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            InitializeDataContext();
        }

        // 페이지를 벗어날 때,
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            UninitializeDataContext();
        }

        private void UninitializeDataContext()
        {
            if (_holidayContext != null)
            {
                _holidayContext.Dispose();
                _holidayContext = null;
            }
        }

        private void CreateDatabase(object state)
        {
            using (HolidayContext db = new HolidayContext(HolidayContext.ConnectionString))
            {
                if (db.DatabaseExists() == false)
                {
                    db.CreateDatabase();
                }
            }
        }

        HolidayContext _holidayContext;
        private void InitializeDataContext()
        {
            CreateDatabase(null);

            _holidayContext = new HolidayContext(HolidayContext.ConnectionString);

            this.MyHolidays = _holidayContext.MyHolidays.ToList();
            EnableDisableButtons();

            this.DataContext = this;
        }

        private void Button_Full_Click(object sender, RoutedEventArgs e)
        {
            InsertHoliday(HolidayType.Full);
        }

        private void Button_Half_Click(object sender, RoutedEventArgs e)
        {
            InsertHoliday(HolidayType.Half);
        }

        private void calendar_DoubleTap(object sender, GestureEventArgs e)
        {
            this._holidayContext.ToggleHoliday(this.SelectedDate);
            EnableDisableButtons();
        }

        private void InsertHoliday(HolidayType holidayType)
        {
            this._holidayContext.InsertMyHoliday(this.SelectedDate, holidayType);
            EnableDisableButtons();
        }

        private void Button_Remove_Click(object sender, RoutedEventArgs e)
        {
            RemoveHoliday(this.SelectedDate);
        }

        private void Button_RemoveList_Click(object sender, RoutedEventArgs e)
        {
            RemoveHoliday(this.SelectedListDate.Date);
        }

        private void RemoveHoliday(DateTime dateTime)
        {
            this._holidayContext.RemoveMyHoliday(true, dateTime);
            EnableDisableButtons();
        }

        Dictionary<DateTime, MyHoliday> _cache;
        public Dictionary<DateTime, MyHoliday> CacheDate
        {
            get { return _cache; }
        }

        public void EnableDisableButtons()
        {
            this.MyHolidays = _holidayContext.MyHolidays.Where(date => date.Date.Year == this.ShowYear).ToList();
            this._cache = this.MyHolidays.ToDictionary(t => t.Date);
            this.MyHolidays.Sort(delegate(MyHoliday p1, MyHoliday p2) 
            { 
                return p1.Date.CompareTo(p2.Date);
            });

            if (this.MyHolidays.Count() == 0)
            {
                this.EmptyMessage = "(Empty)";
            }
            else
            {
                this.EmptyMessage = string.Empty;
            }

            var dates = this.MyHolidays.Where(date => date.Date == this.SelectedDate);
            int selectedCount = dates.Count();

            if (selectedCount > 0)
            {
                this.EnableFullButton = dates.First().Type != HolidayType.Full;
            }
            else
            {
                this.EnableFullButton = true;
            }

            this.EnableHalfButton = (selectedCount == 0);
            this.EnableRemoveButton = (selectedCount != 0);

            this.TotalHolidays = string.Format("{0}: {1} day(s)",
                this.ShowYear, GetHolidayCount(this.MyHolidays));

            this.calendar.Refresh();
        }

        private float GetHolidayCount(List<MyHoliday> list)
        {
            float sum = 0;

            foreach (var item in list)
            {
                if (item.Type == HolidayType.Full)
                {
                    sum++;
                }
                else if (item.Type == HolidayType.Half)
                {
                    sum += 0.5f;
                }
            }

            return sum;
        }

        private void calendar_MonthChanged(object sender, WPControls.MonthChangedEventArgs e)
        {
            if (this.ShowYear != e.Year)
            {
                this.ShowYear = e.Year;
                EnableDisableButtons();
            }
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.EnableListRemoveButton = this.SelectedListDate != null;
        }
    }
}