using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ServiceModel.DomainServices.Client;
using GalaSoft.MvvmLight.Messaging;
using TaskIt.Core;
using TaskIt.Infrastructure;
using TaskIt.Modules.Dashboard.Assets.Resources;
using TaskIt.ViewModels;
using TaskIt.Web;
using Telerik.Windows.Controls.Scheduler;

namespace TaskIt.Modules.Dashboard.ViewModels
{
    [Export]
    public class ProjectsDueThisWeekViewModel : WidgetViewModelBase
    {
        private Appointment _selectedCalendarItem;

        public ProjectsDueThisWeekViewModel()
        {
            LoadData();
            Messenger.Default.Register<ModuleEnum>(this, OnPageEnter);
        }

        private void OnPageEnter(ModuleEnum args)
        {
            if (args == ModuleEnum.Dashboard)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            ShowBusyIndicator();
            DataProvider.GetProjectsDueThisWeek(Utils.CurrentUserID, OnDataLoaded);
        }

        void OnDataLoaded(LoadOperation<Project> lo)
        {
            if (lo.HasError)
            {
                Utils.ShowErrorMessage(DashboardErrorStrings.Message_LoadingProjectsDueThisWeekFailed, lo.Error.Message);               
                lo.MarkErrorAsHandled();
                return;
            }

            ProjectsDueThisWeek = lo.Entities;
            LoadCalendarItems();
            this.OnPropertyChanged(p => p.CalendarItems);
            HideBusyIndicator();
        }

        private void LoadCalendarItems()
        {
            CalendarItems = new DefaultAppointmentCollection();
            foreach (var item in ProjectsDueThisWeek)
            {
                CalendarItems.Add(new Appointment { UniqueId = item.ID.ToString(), Category = Categories.YellowCategory, Subject = item.Name, Start = (DateTime)item.DueDate, End = (DateTime)item.DueDate });
            }
        }

        # region Properties

        private IEnumerable<Project> ProjectsDueThisWeek { get; set; }

        public DefaultAppointmentCollection CalendarItems { get; set; }

        public Appointment SelectedCalendarItem
        {
            get { return _selectedCalendarItem; }
            set { _selectedCalendarItem = value; this.OnPropertyChanged(p => p.SelectedCalendarItem); }
        }

        # endregion

    }
}
