using C1.Xaml.Calendar;
using CalendarData.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace CalendarData
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : CalendarData.Common.LayoutAwarePage
    {
        private AppointmentCollection _appointments = new AppointmentCollection();

        public MainPage()
        {
            this.InitializeComponent();

            // bind C1Calendar to the AppointmentCollection
            calendar.StartTimePath = "Start";
            calendar.EndTimePath = "End";
            calendar.DataSource = _appointments;
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // restore page state
            var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
            if (frameState.ContainsKey("CalendarData"))
            {
                this.LoadState(e.Parameter, (Dictionary<String, Object>)frameState["CalendarData"]);
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // save page state with "CalendarData" key
            var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
            var pageState = new Dictionary<String, Object>();
            this.SaveState(pageState);
            frameState["CalendarData"] = pageState;
        }
 
        protected override void LoadState(object navigationParameter, Dictionary<string, object> pageState)
        {
            base.LoadState(navigationParameter, pageState);
            if (pageState!= null && pageState.Count > 1)
            {
                // restore calendar display and selected dates and appointments
                calendar.DisplayDate = (DateTime)pageState["CalendarDisplayDate"];
                calendar.SelectedDate = (DateTime)pageState["CalendarSelectedDate"];
                foreach (object ob in pageState.Values)
                {
                    if (ob is Appointment)
                    {
                        _appointments.Add(ob as Appointment);
                    }
                }
            }
            Appointment app = navigationParameter as Appointment;
            if (app != null && !_appointments.Contains(app))
            {
                // this is a newaly created appointment, add it to collection
                _appointments.Add(app);
            }
        }

        protected override void SaveState(Dictionary<string, object> pageState)
        {
            // save calendar display and selected dates and appointments
            base.SaveState(pageState);
            pageState.Add("CalendarDisplayDate", calendar.DisplayDate);
            pageState.Add("CalendarSelectedDate", calendar.SelectedDate);
            foreach (Appointment app in _appointments)
            {
                pageState.Add(app.Id.ToString(), app);
            }
        }

        private void calendar_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
        {
            FrameworkElement source = e.OriginalSource as FrameworkElement;
            if (source != null && source.DataContext is DaySlot)
            {
                // create new inplace appointment
                Appointment app = new Appointment();
                app.Start = calendar.SelectedDate;
                app.Duration = TimeSpan.FromDays(1);
                // navigate to appointment edit page
                Frame.Navigate(typeof(AppointmentPage), app);
            }
        }

        private void Appointment_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
        {
            FrameworkElement el = sender as FrameworkElement;
            if (el != null && el.DataContext is Appointment)
            {
                Appointment app = el.DataContext as Appointment;
                // navigate to appointment edit page
                Frame.Navigate(typeof(AppointmentPage), app);
                e.Handled = true;
            }
        }

        private void Appointment_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            // handle appointment removing
            if (e.Key == Windows.System.VirtualKey.Delete)
            {
                ListBox el = sender as ListBox;
                if (el != null && el.SelectedItems.Count > 0 )
                {
                    foreach (Appointment app in el.SelectedItems)
                    {
                        _appointments.Remove(app);
                    }
                }
            }
        }
    }
}
