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 System.Collections.Specialized;
using C1.C1Schedule;
using C1.Silverlight.Data;
using MultiUser.DataService;
using System.IO;

namespace MultiUser
{
	public partial class MainPage : UserControl
	{
		private DataSet _ds = null;
		private DataTable _dtAppointments = null;
		private DataTable _dtEmployees = null;
        private DataTable _dtCustomers = null;

		public MainPage()
		{
			InitializeComponent();
			
			Scheduler.ReminderFire += new EventHandler<ReminderActionEventArgs>(scheduler_ReminderFire);

			Scheduler.GroupItems.CollectionChanged += new NotifyCollectionChangedEventHandler(GroupItems_CollectionChanged);

			// set mappings for the AppointmentStorages
			AppointmentStorage storage = Scheduler.DataStorage.AppointmentStorage;
			storage.Mappings.AppointmentProperties.MappingName = "Properties";
			storage.Mappings.Body.MappingName = "Description";
			storage.Mappings.End.MappingName = "End";
			storage.Mappings.IdMapping.MappingName = "AppointmentId";
			storage.Mappings.Location.MappingName = "Location";
			storage.Mappings.Start.MappingName = "Start";
			storage.Mappings.Subject.MappingName = "Subject";
			storage.Mappings.OwnerIndexMapping.MappingName = "Owner";

			// set mappings for the OwnerStorage
			ContactStorage ownerStorage = Scheduler.DataStorage.OwnerStorage;
            ((INotifyCollectionChanged)ownerStorage.Contacts).CollectionChanged += new NotifyCollectionChangedEventHandler(Owners_CollectionChanged);
            ownerStorage.Mappings.IndexMapping.MappingName = "EmployeeId";
            ownerStorage.Mappings.TextMapping.MappingName = "FirstName";

            // set mappings for the ContactStorage
            ContactStorage cntStorage = Scheduler.DataStorage.ContactStorage;
            ((INotifyCollectionChanged)cntStorage.Contacts).CollectionChanged += new NotifyCollectionChangedEventHandler(Contacts_CollectionChanged);
            cntStorage.Mappings.IdMapping.MappingName = "CustomerId";
            cntStorage.Mappings.TextMapping.MappingName = "CompanyName";

			// load data from server
			LoadData();
		}

		void GroupItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			foreach (SchedulerGroupItem group in Scheduler.GroupItems)
			{
				if (group.Owner != null)
				{
					// set SchedulerGroupItem.Tag property to the data row. That allows to use data row fields in xaml for binding
					int index = (int)group.Owner.Key[0];
					group.Tag = _dtEmployees.Rows.Find(index);
				}
			}
		}

        void Owners_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (Contact cnt in e.NewItems)
                {
                    DataRow row = _dtEmployees.Rows.Find(cnt.Key[0]);
                    if (row != null)
                    {
                        // set Contact.MenuCaption to the FirstName + LastName string
                        cnt.MenuCaption = row["FirstName"].ToString() + " " + row["LastName"].ToString();
                    }
                }
            }
        }

		void Contacts_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.Action == NotifyCollectionChangedAction.Add)
			{
				foreach (Contact cnt in e.NewItems)
				{
					DataRow row = _dtCustomers.Rows.Find(cnt.Key[0]);
					if (row != null)
					{
                        // set Contact.MenuCaption to the CompanyName + Contactname string
						cnt.MenuCaption = row["CompanyName"].ToString() + " (" + row["ContactName"].ToString() + ")";
					}
				}
			}
		}

		// prevent showing reminders
		private void scheduler_ReminderFire(object sender, ReminderActionEventArgs e)
		{
			e.Handled = true;
		}

		#region ** loading data
		// Get data service relative to current host/domain
		DataServiceSoapClient GetDataService()
		{
			// Increase buffer size
			var binding = new System.ServiceModel.BasicHttpBinding();
			binding.MaxReceivedMessageSize = 2147483647; // int.MaxValue
			binding.MaxBufferSize = 2147483647; // int.MaxValue

			// Get absolute service address
			Uri uri = C1.Silverlight.Extensions.GetAbsoluteUri("DataService.asmx");
			var address = new System.ServiceModel.EndpointAddress(uri);

			// Return new service client
			return new DataServiceSoapClient(binding, address);
		}

		void LoadData()
		{
			// Invoke Web service
			var svc = GetDataService();
			svc.GetDataCompleted += svc_GetDataCompleted;
			svc.GetDataAsync("Appointments,Employees,Customers");
		}

		void svc_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
		{
			// Handle errors
			if (e.Error != null)
			{
				tbStatus.Text = "Error downloading data...";
				return;
			}

			// Parse data stream from server (DataSet as XML)
			tbStatus.Text = string.Format(
			  "Got data, {0:n0} kBytes", e.Result.Length / 1024);

			var ms = new MemoryStream(e.Result);
			_ds = new DataSet();
			_ds.EnforceConstraints = false;
			_ds.ReadXml(ms);
			_ds.EnforceConstraints = true;

			// Got the data, find the table
			_dtAppointments = _ds.Tables["Appointments"];
			_dtEmployees = _ds.Tables["Employees"];
            _dtCustomers = _ds.Tables["Customers"];

			// set C1Scheduler data source to the DataTable loaded from server
			Scheduler.DataStorage.AppointmentStorage.DataSource = _dtAppointments;
            Scheduler.DataStorage.ContactStorage.DataSource = _dtCustomers;
            Scheduler.DataStorage.OwnerStorage.DataSource = _dtEmployees;

		}
		#endregion

        private void Scheduler_StyleChanged(object sender, RoutedEventArgs e)
        {
            if (Scheduler.Style == Scheduler.TimeLineStyle)
            {
                // update group header (use different headers for TimeLine and other views)
                Scheduler.GroupHeaderTemplate = (DataTemplate)Resources["myCustomTimeLineGroupHeaderTemplate"];
                btnTimeLine.IsChecked = true;
            }
            else
            {
                // update group header (use different headers for TimeLine and other views)
                Scheduler.GroupHeaderTemplate = (DataTemplate)Resources["myCustomGroupHeaderTemplate"];
                // update toolbar buttons state according to the current C1Scheduler view
                if (Scheduler.Style == Scheduler.WorkingWeekStyle)
                {
                    btnWorkWeek.IsChecked = true;
                }
                else if (Scheduler.Style == Scheduler.WeekStyle)
                {
                    btnWeek.IsChecked = true;
                }
                else if (Scheduler.Style == Scheduler.MonthStyle)
                {
                    btnMonth.IsChecked = true;
                }
                else
                {
                    btnDay.IsChecked = true;
                }
            }
        }

	}
}
