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 System.Windows.Controls.Primitives;

namespace MultipleMonthViewCalender.CustomDatePicker
{

    public class MMVDatepicker : DatePicker
    {
        Popup _popup;
        CustomPopUpCalender _ctrl;
        DateTime _selectedDate = DateTime.Today;

        public MMVDatepicker()
        {
            
        }
        
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            
            //Get the PopUp control of the DatePicker
            this._popup = GetTemplateChild("Popup") as Popup;

            if (this._popup != null)
            {
                this._popup.Opened += new EventHandler(_popup_Opened);
              
            }
        }

      
        void _popup_Opened(object sender, EventArgs e)
        {
            //Get the PopUp Canvas
            Canvas popupCanvas = this._popup.Child as Canvas;

            if (popupCanvas != null)
            {
                if (_ctrl == null)
                {
                    popupCanvas.Children.Clear();

                    //Create the Custom multiple month view calender
                    _ctrl = new CustomPopUpCalender();
                    _ctrl.VerticalAlignment = VerticalAlignment.Stretch;
                    _ctrl.HorizontalAlignment = HorizontalAlignment.Stretch;
                    _ctrl.VerticalContentAlignment = VerticalAlignment.Center;
                    _ctrl.HorizontalContentAlignment = HorizontalAlignment.Center;

                    _ctrl.Calendar_Main.SelectedDatesChanged += new EventHandler<SelectionChangedEventArgs>(Calender_SelectedDatesChanged);
                    _ctrl.Calendar2.SelectedDatesChanged += new EventHandler<SelectionChangedEventArgs>(Calender_SelectedDatesChanged);
                    _popup.LostFocus += new RoutedEventHandler(ctrl_LostFocus);
                    
                    Canvas.SetTop(_ctrl, this.ActualHeight);

                    //Add the calender control to the popup
                    popupCanvas.Children.Add(_ctrl);
                    
                    Dispatcher.BeginInvoke(() =>
                    {
                        _popup.IsOpen = true;

                    });
                }

            }
        }

        void ctrl_LostFocus(object sender, RoutedEventArgs e)
        {
            _popup.IsOpen = false;
        }

        void Calender_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            base.Text = (sender as System.Windows.Controls.Calendar).SelectedDate.Value.ToUniversalTime().ToString("r");
            _popup.IsOpen = false;
        }
    }
}
