namespace inutralia.ViewModels
{
    using inutralia.Models.Questions;
    using MvvmHelpers;
    using System;
    using System.Threading.Tasks;
    using Xamarin.Forms;

    public class QuestionListViewModel : BaseNavigationViewModel
    {
        public QuestionListViewModel() { }

        ObservableRangeCollection<Message> _QuestionList;

        Command _LoadQuestionListCommand;
        Command _RefreshQuestionListCommand;

        public ObservableRangeCollection<Message> QuestionList
        {
            get { return _QuestionList ?? (_QuestionList = new ObservableRangeCollection<Message>()); }
            set
            {
                _QuestionList = value;
                OnPropertyChanged("QuestionList");
            }
        }

        public Command LoadQuestionListCommand
        {
            get { return _LoadQuestionListCommand ?? (_LoadQuestionListCommand = new Command(async () => await ExecuteLoadQuestionListCommand())); }
        }


        public async Task ExecuteLoadQuestionListCommand()
        {
            LoadQuestionListCommand.ChangeCanExecute();
            //if (QuestionList.Count < 1)
            await FetchQuestionList();
            LoadQuestionListCommand.ChangeCanExecute();
        }


        public Command RefreshQuestionListCommand
        {
            get { return _RefreshQuestionListCommand ?? (_RefreshQuestionListCommand = new Command(async () => await ExecuteRefreshQuestionListCommand())); }
        }


        async Task ExecuteRefreshQuestionListCommand()
        {
            try
            {
                RefreshQuestionListCommand.ChangeCanExecute();

                await FetchQuestionList();

                RefreshQuestionListCommand.ChangeCanExecute();
            }
            catch (Exception e)
            {
                string err = e.Message;
            }
        }


        async Task FetchQuestionList()
        {
            IsBusy = true;

            try
            {
                QuestionList = new ObservableRangeCollection<Message>(await App.API.RefreshListAsync<Message>());
            }
            catch (Exception e)
            {
                QuestionList.Clear();
                string err = e.Message;
            }

            IsBusy = false;
        }

    }
}
