using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 Prism.Navigation;
using Prism.Services;
using RestSharp;
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Services;

namespace CafeTerrace.ViewModels
{
    public class PaymentPageViewModel : ViewModelBase
    {
        public ICommand CheckOfferCodeButtonCommand { get; set; }
        public ICommand SubmitOrderButtonCommand { get; set; }
        public ObservableCollection<OrderFood> Foods { get; set; } = new ObservableCollection<OrderFood>();
        private int _praparingMenuiets;
        public int PraparingMenuiets
        {
            get { return _praparingMenuiets; }
            set { SetProperty(ref _praparingMenuiets, value); }
        }

        private string _offerCode;

        public string OfferCode
        {
            get { return _offerCode; }
            set { SetProperty(ref _offerCode, value); }
        }
        private Int64 _unOfferedAmount;
        public Int64 UnOfferedAmount
        {
            get { return _unOfferedAmount; }
            set { SetProperty(ref _unOfferedAmount, value); }
        }
        private Int64 _finalAmount;
        public Int64 FinalAmount
        {
            get { return _finalAmount; }
            set { SetProperty(ref _finalAmount, value); }
        }
        public int DeskNumber { get; set; }
        public ICommand RemoveFood { get; set; }

        public PaymentPageViewModel(INavigationService navigationService, IPageDialogService dialogService) : base(navigationService, dialogService)
        {
            App.BuyBagService.Foods.ForEach(f => Foods.Add(f));
            FinalAmount = Foods.Sum(f => f.CountAmount);
            PraparingMenuiets = Foods.Max(f => f.Food.TimeReady);
            UnOfferedAmount = FinalAmount;
        }

        public override void InitializeCommand()
        {
            base.InitializeCommand();
            try
            {
                CheckOfferCodeButtonCommand = new DelegateCommand<string>(async (offerCode) =>
                {
                    try
                    {
                        Rg.Plugins.Popup.Services.PopupNavigation.Instance.PushAsync(PopUpUtilites.IndicatorPage);
                        RestService<DicountChekcRoot> offerCodeCheckRestService =
                            new RestService<DicountChekcRoot>(Address.BaseAddress);
                        var rootObj = new
                        {
                            UserId = Utilities.Instance.LoginedUser.UserId,
                            DiscountCode = offerCode,
                            TotalAmount = FinalAmount
                        };
                        var rest = await offerCodeCheckRestService.RequestBody(Address.CheckOffer, Method.POST, rootObj,
                            true);
                        if (rest.IsSuccess)
                        {
                            Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopAllAsync(true);
                            if (rest.Data.AmountDiscount == 0)
                            {
                                OfferCode = string.Empty;
                                PageDialogService.DisplayAlertAsync("خطا", "کد تخفیف شما صحیح نمی باشد", "بستن");
                            }
                            else
                            {
                                OfferCode = offerCode;
                                FinalAmount = UnOfferedAmount - rest.Data.AmountDiscount;
                                PageDialogService.DisplayAlertAsync("موفقیت امیز", "کد تخفیف شما صحیح می باشد", "بستن");
                            }
                        }
                        else
                        {
                            OfferCode = string.Empty;
                        }
                    }
                    catch (Exception e)
                    {
                        OfferCode = string.Empty;
                        if (Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopupStack.Count > 0)
                            Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopAsync();
                        if (e is RestServiceExeption)
                        {
                            if ((e as RestServiceExeption).Status == RestStatus.UnAuthorized)
                                NavigationService.NavigateAsync("LoginPage");
                        }

                        PageDialogService.DisplayAlertAsync("خطا", "کد تخفیف اشتباه است یا قبلا استفاده شده است", "بستن");
                    }
                });
                SubmitOrderButtonCommand = new DelegateCommand(async () =>
                {
                    try
                    {
                        if (DeskNumber <= 50 && DeskNumber > 0)
                        {
                            Rg.Plugins.Popup.Services.PopupNavigation.Instance.PushAsync(PopUpUtilites.IndicatorPage);
                            RestService<string> submitOrderRestService = new RestService<string>(Address.BaseAddress);
                            var rootObj = new
                            {
                                DeskNumber = DeskNumber.ToString(),
                                DiscountCode = OfferCode,
                                UserId = Utilities.Instance.LoginedUser.UserId,
                                OrderFoods = (from orderFood in Foods where true select new { orderFood.FoodId, orderFood.CountFood }).ToList()
                            };
                            var rest = await submitOrderRestService.RequestBody(Address.CreateOrder, Method.POST, rootObj,
                                true);
                            if (rest.IsSuccess)
                            {
                                Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopAllAsync(true);
                                var orderViewModel = new SuccessBuyDialogBoxViewModel
                                {
                                    Foods = Foods,
                                    SubmitBuyTime = DateTime.Now,
                                    OfferCode = OfferCode,
                                    IsShow = false,
                                    PrapairingMinuets = Foods.Max(f => f.Food.TimeReady)
                                };

                                Plugin.Settings.CrossSettings.Current.AddOrUpdateValue("Order",
                                    Newtonsoft.Json.JsonConvert.SerializeObject(orderViewModel));

                                foreach (var orderFood in Foods)
                                {
                                    App.BuyBagService.RemoveFood(orderFood);
                                }

                                NavigationService.NavigateAsync("myapp:///NavigationPage/MainPage");
                                await PopupNavigation.Instance.PushAsync(new PopupPage
                                {
                                    Content = new SuccessBuyDialogBox(orderViewModel)
                                });
                            }
                        }
                        else
                        {
                            PageDialogService.DisplayAlertAsync("خطا", "شماره میز شما صحیح نمی باشد", "بستن");
                        }
                    }
                    catch (Exception e)
                    {
                        if (Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopupStack.Count > 0)
                            Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopAsync();
                        if (e is RestServiceExeption)
                        {
                            if ((e as RestServiceExeption).Status == RestStatus.UnAuthorized)
                                NavigationService.NavigateAsync("LoginPage");
                        }
                        PageDialogService.DisplayAlertAsync("خطا", e.Message, "بستن");
                    }
                });
                RemoveFood = new DelegateCommand<OrderFood>(order =>
                {
                    QuestionPopUp questionPopUp = new QuestionPopUp($"ایا از حذف غذا مطمئنید ؟");
                    questionPopUp.Accepted += ((ss, ee) =>
                    {
                        PopupNavigation.Instance.PopAsync();
                        App.BuyBagService.RemoveFood(order);
                        Foods.Remove(order);
                        FinalAmount = Foods.Sum(f => f.CountAmount);
                        if (Foods.Count > 0)
                            PraparingMenuiets = Foods.Max(f => f.Food.TimeReady);
                        else
                            PraparingMenuiets = 0;
                        UnOfferedAmount = FinalAmount;

                    });
                    questionPopUp.Canceled += ((ss, ee) =>
                    {
                        PopupNavigation.Instance.PopAsync();
                    });
                    PopupNavigation.Instance.PushAsync(new PopupPage
                    {
                        Content = questionPopUp,
                        CloseWhenBackgroundIsClicked = false
                    });
                });
            }
            catch (Exception e)
            {
                if (Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopupStack.Count > 0)
                    Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopAsync();
                if (e is RestServiceExeption)
                {
                    if ((e as RestServiceExeption).Status == RestStatus.UnAuthorized)
                        NavigationService.NavigateAsync("LoginPage");
                }
                PageDialogService.DisplayAlertAsync("خطا", e.Message, "بستن");
            }
        }
    }
}
