using System.Collections.Generic;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using MVVMProject.Core;
using MVVMProject.Web;
using MVVMProject.Web.Services;

namespace MVVMProject.ViewModels
{
    public class TasksViewModel : ViewModelBase
    {
        private Task _selectedItem;

        public TasksViewModel()
        {
            DataContext = new DataContext();
            SaveCommand = new DelegateCommand(OnSave);
            LoadTasks();
        }

        public DataContext DataContext { get; set; }

        public DelegateCommand SaveCommand { get; set; }

        public bool IsLoading { get; set; }

        public LoadOperation<Task> LoadTasks()
        {
            // Show the loading message
            IsLoading = true;

            // Get the data via WCF RIA Services. When the call has returned, called OnTasksLoaded.
            return DataContext.Load(DataContext.GetTasksQuery(), OnTasksLoaded, false);
        }

        void OnTasksLoaded(LoadOperation<Task> lo)
        {
            // Hide the loading message
            IsLoading = false;

            // Notify the UI that Tasks and IsLoading properties have changed
            this.OnPropertyChanged(p => p.Tasks);
            this.OnPropertyChanged(p => p.IsLoading);
        }

        public IEnumerable<Task> Tasks
        {
            // Return the Tasks collection from the WCF RIA Services DataContext
            get { return DataContext.Tasks; }
        }

        public Task SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;

                // Let the UI know that the SelectedItem has changed (forces it to re-bind)
                this.OnPropertyChanged(p => p.SelectedItem);
                // Notify the UI, so it can switch to the Details (form) page
                NotifyItemSelected();
            }
        }

        public event RoutedEventHandler ItemSelected;
        public void NotifyItemSelected()
        {
            if (ItemSelected != null) { ItemSelected(this, new RoutedEventArgs()); }
        }

        public void OnSave()
        {
            // Save the changes via WCF RIA Services. When the save is complete, call OnSaveCompleted.
            DataContext.SubmitChanges(OnSaveCompleted, null);
        }

        public virtual void OnSaveCompleted(SubmitOperation so)
        {
            // Clear the item that is selected in the grid (in case we want to select it again)
            SelectedItem = null;
            // Notify the UI, so it can switch back to the List (RadGridView) page
            NotifySaveCompleted();
        } 

        public event RoutedEventHandler SaveCompleted;
        public void NotifySaveCompleted()
        {
            if (SaveCompleted != null) { SaveCompleted(this, new RoutedEventArgs()); }
        }    
    }
}