using GMCabsDriverAssistant.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GMCabsDriverAssistantSolution.ViewModels
{
    [QueryProperty(nameof(PhoneNumber), nameof(PhoneNumber))]
    public class UserRegistrationUpdateDriverPinViewModel : BaseViewModel
    {
        #region Fields
        private string phoneNumber;
        private string pin;
        private string confirmPin;
        private string errorMessage;
        #endregion

        #region Properties
        public string PhoneNumber
        {
            get => phoneNumber;
            set => phoneNumber = value;
        }
        public string Pin
        {
            get => pin;
            set
            {
                SetProperty(ref pin, value);
                ErrorMessage = string.Empty;
            }
        }
        public string ConfirmPin
        {
            get => confirmPin;
            set
            {
                SetProperty(ref confirmPin, value);
                ErrorMessage = string.Empty;
            }
        }
        public string ErrorMessage
        {
            get => errorMessage;
            set => SetProperty(ref errorMessage, value);
        }
        public Command Register { get; set; }
        public Command Back { get; set; }

        #endregion

        #region Constructor
        public UserRegistrationUpdateDriverPinViewModel()
        {
            Register = new Command(OnRegisterClicked);
            Back = new Command(OnBackClicked);
        }

        #endregion

        #region Methods

        private async void OnRegisterClicked(object obj)
        {
            ErrorMessage = "";

            if (string.IsNullOrWhiteSpace(Pin))
            {
                ErrorMessage = "Pin is not entered";
                return;
            }

            if (string.IsNullOrWhiteSpace(ConfirmPin))
            {
                ErrorMessage = "Confirm Pin is not entered";
                return;
            }

            if (Pin != ConfirmPin)
            {
                ErrorMessage = "Pin and Confirm Pin does not match";
                return;
            }

            GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();

            var isDriverPinUpdated = await gmCabsDriverService.UpdateDriverPin(PhoneNumber, Convert.ToInt32(Pin));
            if (!isDriverPinUpdated)
            {
                ErrorMessage = "Pin could be saved. Please try again.";
                return;
            }

            await Shell.Current.GoToAsync($"../../..");
        }

        private async void OnBackClicked(object obj)
        {
            await Shell.Current.GoToAsync("..");
        }
        #endregion
    }
}
