using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using iElection.Models;
using iElection.Models.Dto;
using iElection.Models.Entities;
using iElection.Services.Contracts;
using iElection.Utilities;
using iElection.Views;
using Prism.Navigation;
using Refit;
using Xamarin.Essentials;
using Contact = iElection.Models.Entities.Contact;

namespace iElection.ViewModels
{
    public class AddContactPageViewModel : ViewModelBase<InviteContactDto>
    {
        public RegisterInfoDto InfoDto { get; set; } = new RegisterInfoDto();
        public ICommand SelectContactCommand { get; set; }
        public ICommand AddContactCommand { get; set; }
        public bool IsAdding { get; set; } = true;
        public bool IsReadOnly { get; set; } = false;
        public AddContactPageViewModel(INavigationService navigationService , IRestWrapper restWrapper):base(navigationService ,restWrapper)
        {
            Title = "افزودن مخاطب جدید";
        }

        public override async void Initialize(INavigationParameters parameters)
        {
            base.Initialize(parameters);
            var contact = parameters.GetValue<InviteContactDto>("Contact");
            if (contact != null)
            {
                PageDto = contact;
                IsAdding = false;
                IsReadOnly = true;
                Title = PageDto.FullName;
            }
            else
            {
                try
                {
                    UtilitiesWrapper.Instance.PopUpUtilities.PushIndicator();
                    var rest = await RestWrapper.PageRestApi.GetRegisterInfo(UtilitiesWrapper.Instance.UserUtilities
                        .UserToken);
                    if (rest.IsSuccess)
                    {
                        rest.Data.Genders = new List<GenderItemModel>
                        {
                            new GenderItemModel
                            {
                                Name = "مرد",
                                GenderType = GenderType.Male
                            },
                            new GenderItemModel
                            {
                                Name = "زن",
                                GenderType = GenderType.Female
                            }
                        };
                        InfoDto = rest.Data;
                        await UtilitiesWrapper.Instance.PopUpUtilities.PopAsync();
                    }
                }
                catch (ApiException e)
                {
                    RestWrapper.UnhandledExceptionRaiser(e);
                }
                catch (Exception e)
                {
                    UtilitiesWrapper.Instance.PopUpUtilities.PushError(e.Message);
                }
            }
        }

        public override void InitializeCommand()
        {
            base.InitializeCommand();
            SelectContactCommand = new DelegateCommand(async () =>
            {
                try
                {
                    var contact = await Contacts.PickContactAsync();
                    if (contact == null)
                        return;
                    var firstName = contact.GivenName != null ? contact.GivenName : " ";
                    var lastName = contact.FamilyName != null ? contact.FamilyName : " ";
                    PageDto.FirstName = firstName;
                    PageDto.LastName = lastName;
                    if (contact.Phones == null || contact.Phones.Count <= 0)
                        throw new Exception("مخاطب انتخابی شماره تلفنی ندارد");
                    else
                    {
                        var phone = contact.Phones[0].PhoneNumber;
                        PageDto.Phone = phone;
                    }
                }
                catch (Exception e)
                {
                    UtilitiesWrapper.Instance.PopUpUtilities.PushError(e.Message);
                }
            });
            AddContactCommand = new DelegateCommand(async () =>
            {
                try
                {
                    if (string.IsNullOrEmpty(PageDto.FirstName))
                        throw new Exception("نام را وارد کنید");
                    if (string.IsNullOrEmpty(PageDto.LastName))
                        throw new Exception("نام خانوادگی را وارد کنید");
                    if (string.IsNullOrEmpty(PageDto.Phone))
                        throw new Exception("شماره تلفن را وارد کنید");
                    if (PageDto.JobId <= 0)
                        throw new Exception("شغل را وارد کنید");
                    if (PageDto.DistrictId <= 0)
                        throw new Exception("محله را وارد کنید");
                    var rest = await RestWrapper.CrudApiRest<InviteContactDto, int>(Address.ContactController)
                        .Create(PageDto, UtilitiesWrapper.Instance.UserUtilities.UserToken);
                    if (rest.IsSuccess)
                    {
                        UtilitiesWrapper.Instance.PopUpUtilities.PushSuccess("افزودن مخاطب با موفقیت انجام شد");
                    }
                }
                catch (ApiException e)
                {
                    RestWrapper.UnhandledExceptionRaiser(e);
                }
                catch (Exception e)
                {
                    UtilitiesWrapper.Instance.PopUpUtilities.PushError(e.Message);
                }
            });
        }
    }
}
