namespace inutralia.ViewModels
{
    using inutralia.Models.Questions;
    using MvvmHelpers;
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Windows.Input;
    using Xamarin.Forms;

    public class NewQuestionViewModel : BaseNavigationViewModel
    {
        public enum Estatus
        {
            Pendiente = 1,
            Respondida_por_cliente = 2,
            Respondida_por_nutricionista = 3,
            Cerrado = 4
        }

        public Estatus State => (Estatus)Message?.StateId;

        public Message Message { private set; get; }

        public ICommand SendCommand { get; set; }

        public ObservableRangeCollection<Message> _ListMessages;

        // LOADING LIST
        Command _LoadNewQuestionCommand;

        // UODATE LIST
        Command _RefreshNewQuestionCommand;

        // DELETE LIST
        Command _DeleteNewQuestionCommand;


        public NewQuestionViewModel()
        {
            IsBusy = true;

            ListMessages = new ObservableRangeCollection<Message>();

            SendCommand = new Command(() =>
            {
                if (!String.IsNullOrWhiteSpace(OutText))
                {
                    var message = new Message
                    {
                        Text = OutText,
                        IsTextIn = false,
                        MessageDateTime = DateTime.Now
                    };

                    ListMessages.Add(message);
                    OutText = "";
                }
            });

            IsBusy = false;
        }

        public string OutText
        {
            get { return _outText; }
            set { SetProperty(ref _outText, value); }
        }
        string _outText = string.Empty;



        // LIST MESSAGES
        public ObservableRangeCollection<Message> ListMessages
        {
            get { return _ListMessages ?? (_ListMessages = new ObservableRangeCollection<Message>()); }
            set
            {
                _ListMessages = value;
                OnPropertyChanged("ListMessages");
            }
        }


        // LOAD
        public Command LoadNewQuestionCommand
        {
            get { return _LoadNewQuestionCommand ?? (_LoadNewQuestionCommand = new Command(async () => await ExecuteLoadNewQuestionCommand())); }
        }

        public async Task ExecuteLoadNewQuestionCommand()
        {
            LoadNewQuestionCommand.ChangeCanExecute();
            //if (Authorizations.Count < 1)
            await FetchNewQuestion();
            LoadNewQuestionCommand.ChangeCanExecute();
        }


        // REFRESH
        public Command RefreshNewQuestionCommand
        {
            get { return _RefreshNewQuestionCommand ?? (_RefreshNewQuestionCommand = new Command(async () => await ExecuteRefreshNewQuestionCommand())); }
        }

        public async Task ExecuteRefreshNewQuestionCommand()
        {
            try
            {
                RefreshNewQuestionCommand.ChangeCanExecute();
                await FetchNewQuestion();
                RefreshNewQuestionCommand.ChangeCanExecute();

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


        // DELETE
        public Command DeleteNewQuestionCommand
        {
            get
            {
                return _DeleteNewQuestionCommand ?? (_DeleteNewQuestionCommand = new Command(async (parameter) => await ExecuteDeleteNewQuestionCommand(parameter as Message)));
            }
        }

        async Task ExecuteDeleteNewQuestionCommand(Message message)
        {
            if (message != null)
            {
                IsBusy = true;
                await App.API.DeleteItemAsync(message);
                await FetchNewQuestion();
                IsBusy = false;
            }
        }


        // FETCH
        async Task FetchNewQuestion()
        {
            IsBusy = true;
            try
            {
                ListMessages = new ObservableRangeCollection<Message>(await App.API.RefreshListAsync<Message>());
            }
            catch (Exception e)
            {
                string err = e.Message;
            }
        }


        // SAVE MESSAGE
        public async Task SaveMessage(string text)
        {
            var q = Message;
            HttpMethod method = HttpMethod.Post;

            IsBusy = true;

            if (q.Id < 0)
            {
                var data = new Dictionary<string, string>()
                {
                    {"subject", q.Subject },{"message", text}
                };
                await App.API.RawMessage(method, string.Format("messages"), data, q);
            }

            IsBusy = false;

            ListMessages = new ObservableRangeCollection<Message>();
        }


        // UPDATE MESSAGE
        public async Task UpdateMessage()
        {
            var q = Message;
            HttpMethod method = HttpMethod.Post;

            IsBusy = true;
            await App.API.UpdateItemAsync(q);

            if (await App.API.RefreshItemAsync(Message))
            {
                Title = Message.StatusImg;
                OnPropertyChanged("State");
            }

            IsBusy = false;
        }


        // REFRESH MESSAGE
        public async Task RefreshData()
        {
            if ((Message == null) || (Message.Id < 0))
                return;

            IsBusy = true;
            if (await App.API.RefreshItemAsync(Message))
            {
                Title = Message.StatusImg;
                OnPropertyChanged("State");
            }
            IsBusy = false;

            await FetchNewQuestion();
        }


        public bool IsClosedOrPending => (State == Estatus.Pendiente ||
                                          State == Estatus.Cerrado ||
                                          State == Estatus.Respondida_por_cliente ||
                                          State == Estatus.Respondida_por_nutricionista);

        public bool MayBeClosed => !IsClosedOrPending;
    }
}
