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.Help.Assets.Resources;
using TaskIt.Web;

namespace TaskIt.Modules.Help.ViewModels
{
    [Export]
    public class BlogPostsViewModel : TasksWidgetViewModelBase
    {
        private Task _selectedItem;

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

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

        private void LoadData()
        {
            ShowBusyIndicator();
            DataProvider.GetCompletedBlogPosts(OnBlogPostsLoaded);
        }

        void OnBlogPostsLoaded(LoadOperation<Task> lo)
        {
            if (lo.HasError)
            {
                Utils.ShowErrorMessage(ErrorStrings.Message_LoadingBlogPostsFailed, lo.Error.Message);
                lo.MarkErrorAsHandled();
                return;
            }

            BlogPosts = lo.Entities;
            this.OnPropertyChanged(m => m.BlogPosts);
            HideBusyIndicator();
        }

        # region Properties

        public IEnumerable<Task> BlogPosts { get; set; }

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

        # endregion

    }
}