using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using iElection.Models.Api;
using iElection.Services.Contracts;
using iElection.Utilities;
using iElection.Views.PopUps;
using Prism.Navigation;
using Refit;

namespace iElection.ViewModels
{
    public class LoginPageViewModel : ViewModelBase<LoginRequest>
    {
        public ICommand SignUpCommand { get; set; }
        public ICommand LoginCommand { get; set; }
        public ICommand ForgetPassCommand { get; set; }
        public LoginPageViewModel(INavigationService navigationService, IRestWrapper restWrapper) : base(navigationService, restWrapper)
        {

        }

        public override void InitializeCommand()
        {
            base.InitializeCommand();
            LoginCommand = new DelegateCommand( async () =>
            {
                try
                {
                    UtilitiesWrapper.Instance.PopUpUtilities.PushIndicator();
                    if (string.IsNullOrEmpty(PageDto.Phone))
                        throw new Exception("شماره تلفن خود را وارد کنید");
                    if (string.IsNullOrEmpty(PageDto.Password))
                        throw new Exception("رمز عبور خود را وارد کنید");
                    var rest = await RestWrapper.AccountApiRest.LoginUser(PageDto);
                    if (rest.IsSuccess)
                    {
                        UtilitiesWrapper.Instance.PopUpUtilities.PopAsync();
                        UtilitiesWrapper.Instance.UserUtilities.UserToken = "Bearer " + rest.Data.jwt;
                        UtilitiesWrapper.Instance.UserUtilities.FullName = rest.Data.fullName;
                        await NavigationService.NavigateAsync("myapp:///NavigationPage/MainPage");
                    }
                }
                catch (ApiException e)
                {
                    RestWrapper.UnhandledExceptionRaiser(e);
                }
                catch (Exception e)
                {
                    UtilitiesWrapper.Instance.PopUpUtilities.PushError(e.Message);
                }
            });
            SignUpCommand = new DelegateCommand( () =>
            {
                 NavigationService.NavigateAsync("SignUpPage");
            });
            ForgetPassCommand = new DelegateCommand(async () =>
            {
                await UtilitiesWrapper.Instance.PopUpUtilities.PushAsync(new ForegetPassPopUp());
            });
        }
    }
}
