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.Data;
using System.Globalization;

namespace CustomGroupingView
{
    public partial class MainPage : UserControl, IDisposable
    {
        public MainPage()
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            InitializeComponent();
            // add some contacts
            Contact cnt = new Contact();
            cnt.Text = "Andy Garcia";
            sched1.DataStorage.ContactStorage.Contacts.Add(cnt);
            cnt = new Contact();
            cnt.Text = "Nancy Drew";
            sched1.DataStorage.ContactStorage.Contacts.Add(cnt);
            cnt = new Contact();
            cnt.Text = "Robert Clark";
            sched1.DataStorage.ContactStorage.Contacts.Add(cnt);
            cnt = new Contact();
            cnt.Text = "James Doe";
            sched1.DataStorage.ContactStorage.Contacts.Add(cnt);
            sched1.GroupBy = "Contact";
            sched1.VisibleGroupItems.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(VisibleGroupItems_CollectionChanged);
        }

        void VisibleGroupItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            // update CanExecute state for buttons
            C1.Silverlight.CommandManager.InvalidateRequerySuggested();
        }
        
        #region IDisposable Members

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

        #endregion

    }

    /// <summary>
    /// Represents a Binding converter that returns a <see cref="Boolean"/> value 
    /// indicating whether a source value is today's date.
    /// </summary>
    /// <remarks>
    /// <see cref="IsTodayConverter"/> is a one-way converter. 
    /// </remarks>
    public class IsTodayVisibilityConverter : IValueConverter
    {
        /// <summary>
        /// Converts a value. The data binding engine calls this method 
        /// when it propagates a value from the binding source to the binding target. 
        /// </summary>
        /// <param name="value">The value produced by the binding source.</param>
        /// <param name="targetType">The type of the binding target property.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>A converted value.</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Visibility result = Visibility.Collapsed;
            if (value != null && (value is DateTime) && ((DateTime)value).Date == DateTime.Today)
            {
                result = Visibility.Visible;
            }

            if ( !string.IsNullOrEmpty((string)parameter))
            {
                // invert result
                result = result == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
            }
            return result;
        }
        /// <summary>
        /// Returns Binding.DoNothing. 
        /// </summary>
        /// <param name="value">The value that is produced by the binding target.</param>
        /// <param name="targetType">The type to convert to.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>A converted value.</returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

    /// <summary>
    /// Returns VisualIntervalCollection for the specified day and specified SchedulerGroup which can be used
    /// as an ItemsSource for VisualIntervalsPresenter control.
    /// </summary>
    /// <remarks>
    /// If converter Parameter property is "Self", returns list of a single VisualIntervalGroup, to use it as ItemsSource for representing all-day area.
    /// In all other cases returns VisualItervalCollection containing time slots for the single day.
    /// </remarks>
    public class ItemsSourceRetriever : FrameworkElement
    {
        public ItemsSourceRetriever()
        {
            Visibility = System.Windows.Visibility.Collapsed;
            
        }

        public string Parameter { get; set; }

        public object ItemsSource
        {
            get { return (object)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ItemsSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(object), typeof(ItemsSourceRetriever), null);

        public object SchedulerGroup
        {
            get { return (object)GetValue(SchedulerGroupProperty); }
            set { SetValue(SchedulerGroupProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SchedulerGroup.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SchedulerGroupProperty =
            DependencyProperty.Register("SchedulerGroup", typeof(object), typeof(ItemsSourceRetriever), 
            new PropertyMetadata(null, new PropertyChangedCallback(OnSchedulerGroupChanged)));

        private static void OnSchedulerGroupChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ItemsSourceRetriever r = d as ItemsSourceRetriever;
            r.OnSchedulerGroupChanged();

        }
        private void OnSchedulerGroupChanged()
        {
            SchedulerGroupItem group = SchedulerGroup as SchedulerGroupItem;
            int index = -1;
            if (group != null)
            {
                ItemsControl itm = VTreeHelper.GetParentOfType(this, typeof(ItemsControl)) as ItemsControl;
                if (itm != null)
                {
                    object data = itm.DataContext;

                    ItemsControl itmParent = VTreeHelper.GetParentOfType(itm, typeof(ItemsControl)) as ItemsControl;
                    if (itmParent != null)
                    {
                        index = itmParent.Items.IndexOf(data);
                        VisualIntervalGroup visualIntervalGroup = group.VisualIntervalGroups[index] as VisualIntervalGroup;
                        if (Parameter.ToLower() == "self")
                        {
                            // create list of a single VisualIntervalGroup
                            // (we need list to use it as ItemsSource)
                            List<object> list = new List<object>();
                            list.Add(visualIntervalGroup);
                            ItemsSource = list;
                        }
                        else
                        {
                            ItemsSource = visualIntervalGroup.VisualIntervals;
                        }
                    }
                }
            }
        }
    }
}
