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 C1.Silverlight.Schedule;
using C1.C1Schedule;
using C1.Silverlight;
using System.Windows.Printing;

namespace AdvancedIntervalAppointment
{
    public partial class MainPage : UserControl, IDisposable
    {
        public MainPage()
        {
            InitializeComponent();
            
            // initialize palette combo
            paletteBox.SelectedIndex = 0;

            Appointment app = new Appointment(DateTime.Today.AddDays(-1), TimeSpan.FromDays(1));
            app.AllDayEvent = true;
            app.Private = true;
            app.Subject = "Test All-Day Event";
            app.Label = sched1.DataStorage.LabelStorage.Labels[8];
            app.Location = "Room 15";
            sched1.DataStorage.AppointmentStorage.Appointments.Add(app);
            app = new Appointment(DateTime.Today, TimeSpan.FromDays(1));
            app.AllDayEvent = true;
            app.BusyStatus = sched1.DataStorage.StatusStorage.Statuses[StatusTypeEnum.Tentative];
            app.Subject = "Another test All-Day Event";
            app.Label = sched1.DataStorage.LabelStorage.Labels[7];
            app.Location = "Room 22";
            sched1.DataStorage.AppointmentStorage.Appointments.Add(app);
            app = new Appointment();
            app.Duration = TimeSpan.FromMinutes(60);
            app.Subject = "Test Appointment";
            app.Location = "Room 327";
            app.Label = sched1.DataStorage.LabelStorage.Labels[5];
            sched1.DataStorage.AppointmentStorage.Appointments.Add(app);
            app = new Appointment();
            app.Duration = TimeSpan.FromMinutes(20);
            app.Subject = "Another test Appointment";
            app.Location = "Room 327";
            app.BusyStatus = sched1.DataStorage.StatusStorage.Statuses[StatusTypeEnum.OutOfOffice];
            sched1.DataStorage.AppointmentStorage.Appointments.Add(app);
            app = new Appointment(DateTime.Today.AddDays(-3).AddHours(11), TimeSpan.FromMinutes(60));
            app.Subject = "Silverlight lesson";
            app.Location = "Conference room";
            app.Label = sched1.DataStorage.LabelStorage.Labels[8];
            RecurrencePattern pattern = app.GetRecurrencePattern();
            pattern.RecurrenceType = RecurrenceTypeEnum.Weekly;
            pattern.DayOfWeekMask = WeekDaysEnum.Monday;
            pattern.Occurrences = 5;
            sched1.DataStorage.AppointmentStorage.Appointments.Add(app);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            // update toolbar buttons state
            sched1_StyleChanged(null, null);
        }
        
        private void btnToday_Click(object sender, RoutedEventArgs e)
        {
            sched1.VisibleDates.BeginUpdate();
            sched1.VisibleDates.Clear();
            sched1.VisibleDates.Add(DateTime.Today);
            sched1.VisibleDates.EndUpdate();
        }

        void sched1_LayoutUpdated(object sender, EventArgs e)
        {
            // update IntervalAppointmentTemplate for all AppointmentsCoverPanes in the control template
            // (you can use different templates for different views, or for AppointmentsCoverPanes with different orientation)
            if (needUpdateIntervalAppointmentTemplate)
            {
                IList<DependencyObject> list = new List<DependencyObject>();
                VTreeHelper.GetChildrenOfType(sched1, typeof(AppointmentsCoverPane), ref list);
                foreach (AppointmentsCoverPane pane in list)
                {
                    pane.IntervalAppointmentTemplate = sched1.IntervalAppointmentTemplate;
                }
                needUpdateIntervalAppointmentTemplate = false;
            }
        }

        bool needUpdateIntervalAppointmentTemplate = false;
        private void sched1_StyleChanged(object sender, RoutedEventArgs e)
        {
            // update toolbar buttons state according to the current C1Scheduler view
            if (sched1.Style == sched1.WorkingWeekStyle)
            {
                btnWorkWeek.IsChecked = true;
            }
            else if (sched1.Style == sched1.WeekStyle)
            {
                btnWeek.IsChecked = true;
            }
            else if (sched1.Style == sched1.MonthStyle)
            {
                btnMonth.IsChecked = true;
            }
            else if (sched1.Style == sched1.TimeLineStyle)
            {
                btnTimeLine.IsChecked = true;
            }
            else
            {
                btnDay.IsChecked = true;
            }
            if (sched1.Style != sched1.MonthStyle)
            {
                needUpdateIntervalAppointmentTemplate = true;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            sched1.Dispose();
        }

        #endregion

    }

    /// <summary>
    /// The <see cref="CustomAppPresenter"/> class overrides tooltip behavior and adds context menu
    /// </summary>
    [TemplateVisualState(Name = "MouseOver", GroupName = "CommonStates")]
    [TemplateVisualState(Name = "Normal", GroupName = "CommonStates")]
    public class CustomAppPresenter : IntervalAppointmentPresenter
    {
        public CustomAppPresenter()
        {
        }

        ToolTip _tip;

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            // add context menu
            C1ContextMenu menu = new C1ContextMenu();
            C1MenuItem item = new C1MenuItem();
            item.Header = "Open";
            menu.Items.Add(item);
            item = new C1MenuItem();
            item.Header = "Remove";
            menu.Items.Add(item);
            item = new C1MenuItem();
            item.Header = "Print";
            menu.Items.Add(item);
            C1ContextMenuService.SetContextMenu(this, menu);
            menu.ItemClick += new EventHandler<SourcedEventArgs>(menu_ItemClick);

            _tip = ToolTipService.GetToolTip(this) as ToolTip;
            if (_tip != null)
            {
                // remove default tooltip
                ToolTipService.SetToolTip(this, null);
            }
            _tip = new ToolTip();
            _tip.Opened += new RoutedEventHandler(tip_Opened);
            ToolTipService.SetToolTip(this, _tip);

        }

        void tip_Opened(object sender, RoutedEventArgs e)
        {
            // DataContext here is IntervalAppointment object
            // IntervalAppointment.Appointment property represents the source appointment
            // so you can look at appointment properties here and change tooltip content
            _tip.Content = Appointment.Subject + " " + Appointment.Body + " - it's my custom tooltip";
            _tip.IsOpen = true;
        }

        void menu_ItemClick(object sender, SourcedEventArgs e)
        {
            C1MenuItem item = e.Source as C1MenuItem;
            C1Menu menu = sender as C1Menu;

            if (((string)item.Header).Equals("Print"))
            {
                // print appointment
                PrintDocument prt = new PrintDocument();
                prt.PrintPage += (s, args) =>
                {
                    // create document content (single page)
                    TextBlock text = new TextBlock();
                    text.TextWrapping = System.Windows.TextWrapping.Wrap;
                    text.Width = 500;
                    text.Text = Appointment.Start.ToString("f") + " - " + Appointment.End.ToShortTimeString()
                                + "\r\n" + Appointment.Subject + " " + Appointment.Location 
                                + "\r\n" + Appointment.Body;
                    args.PageVisual = text;
                };
                prt.Print(string.IsNullOrEmpty(Appointment.Subject) ? "Unnamed appointment" : Appointment.Subject);
            }
            else if (((string)item.Header).Equals("Remove"))
            {
                // remove appointment
                Appointment.Delete();
            }
            else if (((string)item.Header).Equals("Open"))
            {
                // show Appointment dialog
                C1Scheduler sched = VTreeHelper.GetParentOfType(this, typeof(C1Scheduler), false) as C1Scheduler;
                if (sched != null)
                {
                    sched.EditAppointmentDialog(Appointment);
                }
            }
        }

        protected override void OnMouseEnter(MouseEventArgs e)
        {
            base.OnMouseEnter(e);
            VisualStateManager.GoToState(this, "MouseOver", true);
        }

        protected override void OnMouseLeave(MouseEventArgs e)
        {
            base.OnMouseLeave(e);
            VisualStateManager.GoToState(this, "Normal", true);
        }
    }

}
