using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using CafeTerrace.Models;
using CafeTerrace.Models.Api;
using CafeTerrace.Models.DataBase;
using CafeTerrace.Services;
using CafeTerrace.Utilities;
using CafeTerrace.Views.DialogBox;
using CafeTerrace.Views.PopUps;
using Newtonsoft.Json;
using Plugin.Settings;
using Plugin.Settings.Abstractions.Extensions;
using Prism.Navigation;
using Prism.Services;
using RestSharp;
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Services;

namespace CafeTerrace.ViewModels
{
    public class ProfilePageViewModel : ViewModelBase
    {
        private SuccessBuyDialogBoxViewModel _successBuyDialogBoxViewModel;

        public SuccessBuyDialogBoxViewModel SuccessBuyDialogBoxViewModel
        {
            get { return _successBuyDialogBoxViewModel; }
            set { SetProperty(ref _successBuyDialogBoxViewModel, value); }
        }
        public ICommand BackButtonCommand { get; set; }
        public ICommand EditUserButtonCommand { get; set; }
        public ICommand CloseUserButtonCommand { get; set; }
        public ICommand AddBirthDateCommand { get; set; }
        public ICommand OpenJobDialogCommand { get; set; }

        private Job _selectedJob;

        public Job SelectedJob
        {
            get { return _selectedJob; }
            set { SetProperty(ref _selectedJob, value); }
        }


        private bool _showPayment = false;
        public bool ShowPayemnt
        {
            get { return _showPayment; }
            set { SetProperty(ref _showPayment, value); }
        }

        private User _user;
        public User SignUpUser
        {
            get { return _user; }
            set { SetProperty(ref _user, value); }
        }

        private ProfileRoot profileRoot;

        public ProfileRoot ProfileRoot
        {
            get { return profileRoot; }
            set { SetProperty(ref profileRoot, value); }
        }

        public ICommand RemoveBirthDate { get; set; }


        public ProfilePageViewModel(INavigationService navigationService, IPageDialogService dialogService) : base(navigationService, dialogService)
        {

        }

        public override void InitializeCommand()
        {
            base.InitializeCommand();
            RemoveBirthDate = new DelegateCommand<UserBirthDate>(birthDate =>
            {
                QuestionPopUp questionPopUp = new QuestionPopUp($"می خواهید تاریخ را حذف کنید ؟");
                questionPopUp.Accepted += (async(ss, ee) =>
                {
                    PopupNavigation.Instance.PopAsync();
                    try
                    {
                        PopupNavigation.Instance.PushAsync(PopUpUtilites.IndicatorPage);
                        RestService<string> restService = new RestService<string>(Address.BaseAddress);
                        var res = await restService.RequestBody($"{Address.DeleteBirthDate}", Method.POST, birthDate, true);
                        PopupNavigation.Instance.PopAllAsync();
                        if (res.IsSuccess)
                        {
                            PopupNavigation.Instance.PopAllAsync();
                            init();
                        }
                    }
                    catch (Exception exception)
                    {
                        PopupNavigation.Instance.PopAllAsync();
                        PopUpUtilites.ErrorPage(exception.Message);
                    }

                });
                questionPopUp.Canceled += ((ss, ee) =>
                {
                    PopupNavigation.Instance.PopAsync();
                });
                PopupNavigation.Instance.PushAsync(new PopupPage
                {
                    Content = questionPopUp,
                    CloseWhenBackgroundIsClicked = false
                });
            });
            BackButtonCommand = new DelegateCommand(() => { NavigationService.GoBackAsync(); });
            EditUserButtonCommand = new DelegateCommand(async() =>
            {
                if (SignUpUser != null)
                {
                    try
                    {

                        var LogindUser = Instance.LoginedUser;
                        PopupNavigation.Instance.PushAsync(PopUpUtilites.IndicatorPage);
                        RestService<User> restService = new RestService<User>(Address.BaseAddress);
                        var res = await restService.RequestBody($"{Address.EditUser}/{LogindUser.UserId}", Method.PUT,SignUpUser,true);
                        PopupNavigation.Instance.PopAllAsync();
                        if (res.IsSuccess)
                        {
                            //SignUpUser = res.Data;
                            PageDialogService.DisplayAlertAsync("موفقیت امیز", "اطلاعات شما تغییر پیدا کرد", "بستن");
                        }
                    }
                    catch (Exception e)
                    {
                        if (PopupNavigation.Instance.PopupStack.Count > 0)
                            PopupNavigation.Instance.PopAllAsync();
                        if (e is RestServiceExeption)
                        {
                            if ((e as RestServiceExeption).Status == RestStatus.UnAuthorized)
                                NavigationService.NavigateAsync("LoginPage");
                        }
                        PageDialogService.DisplayAlertAsync("خطا", e.Message, "بستن");
                    }
                }
            });
            AddBirthDateCommand = new DelegateCommand(() =>
            {
                var dialog = new AddBirthDateDialogBox();
                dialog.Added += ((ss, ee) => { init(); });
                PopupNavigation.Instance.PushAsync(new PopupPage
                {
                    Content = dialog,
                    CloseWhenBackgroundIsClicked = true
                });
            });
            CloseUserButtonCommand = new DelegateCommand(() =>
            {
                QuestionPopUp questionPopUp = new QuestionPopUp($"می خواهید از حساب خود خارج شوید ؟");
                questionPopUp.Accepted += (async (ss, ee) =>
                {
                    PopupNavigation.Instance.PopAsync();
                    Plugin.Settings.CrossSettings.Current.Remove("LoginedUser");
                    NavigationService.NavigateAsync("myapp:///NavigationPage/LoginPage");
                    App.BuyBagService.Foods.Clear();
                });
                questionPopUp.Canceled += ((ss, ee) =>
                {
                    PopupNavigation.Instance.PopAsync();
                });
                PopupNavigation.Instance.PushAsync(new PopupPage
                {
                    Content = questionPopUp,
                    CloseWhenBackgroundIsClicked = false
                });

            });
            OpenJobDialogCommand = new DelegateCommand(async() =>
            {
                try
                {
                    PopupNavigation.Instance.PushAsync(PopUpUtilites.IndicatorPage);
                    RestService<List<Job>> restService = new RestService<List<Job>>(Address.BaseAddress);
                    var res = await restService.RequestParameters($"{Address.GetJobs}", Method.GET, new Dictionary<string, string>(), true);
                    await PopupNavigation.Instance.PopAllAsync();
                    if (res.IsSuccess)
                    {
                        var jobdialog = new JobDialogBox(res.Data);
                        jobdialog.JobSelected += ((job, ee) =>
                        {
                            SelectedJob = (Job)job;
                            SignUpUser.JobId = SelectedJob.JobId;
                            PopupNavigation.Instance.PopAsync();
                        });
                        await PopupNavigation.Instance.PushAsync(new PopupPage
                        {
                            Content = jobdialog,
                            CloseWhenBackgroundIsClicked = true
                        });
                    }
                }
                catch (Exception e)
                {
                    PopupNavigation.Instance.PopAllAsync();
                    PopupNavigation.Instance.PushAsync(PopUpUtilites.ErrorPage(e.Message));
                }
            });
        }

        public override void Initialize(INavigationParameters parameters)
        {
            
            base.Initialize(parameters);
            init();
        }

        private async void init()
        {
            try
            {
                var LogindUser = Instance.LoginedUser;

                PopupNavigation.Instance.PushAsync(PopUpUtilites.IndicatorPage);
                RestService<ProfileRoot> restService = new RestService<ProfileRoot>(Address.BaseAddress);
                var res = await restService.RequestParameters($"{Address.GetUserProfile}/{LogindUser.UserId}", Method.GET, new Dictionary<string, string>(), true);
                PopupNavigation.Instance.PopAllAsync();
                if (res.IsSuccess)
                {
                    res.Data.User.Phone = res.Data.User.UserName;
                    SignUpUser = res.Data.User;
                    SelectedJob = res.Data.User.Job;
                    res.Data.Orders = res.Data.Orders.OrderBy(o => o.Register).ToList();
                    ProfileRoot = res.Data;
                }
            }
            catch (Exception e)
            {
                if (PopupNavigation.Instance.PopupStack.Count > 0)
                    PopupNavigation.Instance.PopAllAsync();
                if (e is RestServiceExeption)
                {
                    if ((e as RestServiceExeption).Status == RestStatus.UnAuthorized)
                        NavigationService.NavigateAsync("LoginPage");
                }
                PageDialogService.DisplayAlertAsync("خطا", e.Message, "بستن");
            }
        }
    }
}
