﻿using System;
using Xamarin.Forms;
using System.Collections.Generic;
using System.Windows.Input;
using XamarinTodoProject.Common;
using XamarinTodoProject.Enum;
using XamarinTodoProject.Model;
using XamarinTodoProject.Repository;
using XamarinTodoProject.View;

namespace XamarinTodoProject.ViewModel
{
    public class TodoListPageViewModel : BaseViewModel, IDisposable
    {
        private ITodoListRepository _todoListRepository;
        private INavigation _navigation;
        private TodoList _selectedTodoList;
        private ICollection<TodoList> _todoLists;
        private ICommand _addTodoListCommand;

        public string Title
        {
            get
            {
                return "Todo Lists";
            }
        }

        public TodoList SelectedTodoList
        {
            get
            {
                return _selectedTodoList;
            }
            set
            {
                _selectedTodoList = value;

                if (_selectedTodoList != null)
                {
                    _navigation.PushAsync(new TodoListItemsPage(_selectedTodoList));
                    _selectedTodoList = null;
                    OnPropertyChanged(nameof(SelectedTodoList));
                }
            }
        }

        public ICollection<TodoList> TodoLists
        {
            get
            {
                return _todoLists;
            }
            set
            {
                _todoLists = value;
                OnPropertyChanged(nameof(TodoLists));
            }
        }

        public ICommand AddTodoListCommand
        {
            get
            {
                if (_addTodoListCommand == null)
                {
                    _addTodoListCommand = new Command(RedirectToAddTodoListPage);
                }

                return _addTodoListCommand;
            }
        }


        public TodoListPageViewModel(INavigation navigation)
        {
            _navigation = navigation;
            _todoListRepository = (App.Current as App).TodoListRepository;

            MessagingCenter.Subscribe<AddTodoListPageViewModel>(this, ModelMessage.ModelChanged, async (sender) =>
            {
                TodoLists = await _todoListRepository.GetAsync();
            });
        }

        public async void InitializeData()
        {
            if (TodoLists == null)
            {
                TodoLists = await _todoListRepository.GetAsync();
            }
        }

        public void RedirectToAddTodoListPage()
        {
            _navigation.PushAsync(new AddTodoListPage());
        }

        public void Dispose()
        {
            MessagingCenter.Unsubscribe<AddTodoListPageViewModel>(this, ModelMessage.ModelChanged);
        }
    }
}
