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 Prism.Navigation;
using Refit;

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

        }

        public override void InitializeCommand()
        {
            base.InitializeCommand();
            LoginCommand = new DelegateCommand( async () =>
            {
                try
                {
                    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.UserUtilities.UserToken = "Bearer " + rest.Data.jwt;
                        await NavigationService.NavigateAsync("MainPage");
                    }
                }
                catch (ApiException e)
                {
                    RestWrapper.UnhandledExceptionRaiser(e);
                }
                catch (Exception e)
                {
                    UtilitiesWrapper.Instance.PopUpUtilities.PushError(e.Message);
                }
            });
            SignUpCommand = new DelegateCommand( () =>
            {
                 NavigationService.NavigateAsync("SignUpPage");
            });
        }
    }
}
