using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CafeTerrace.Dependencies;
using CafeTerrace.Models;
using CafeTerrace.Models.Api;
using CafeTerrace.Models.DataBase;
using CafeTerrace.Services;
using CafeTerrace.Utilities;
using CafeTerrace.ViewModels;
using MD.PersianDateTime.Standard;
using RestSharp;
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace CafeTerrace.Views.DialogBox
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class AddBirthDateDialogBox : ContentView
    {
        private DateTime birthdate;
        public event EventHandler Added;
        public AddBirthDateDialogBox()
        {
            InitializeComponent();
        }

        private void BirthDayEntry_OnFocused(object sender, FocusEventArgs e)
        {
            try
            {
                var datePickerDialog = new PersianDatePicker();
                PopupNavigation.Instance.PushAsync(new PopupPage
                {
                    Content = datePickerDialog,
                    CloseWhenBackgroundIsClicked = false
                });
                datePickerDialog.DateSelected += ((date, ee) =>
                {
                    birthDayEntry.Text = (new PersianDateTime((DateTime)date)).ToLongDateString();
                    birthdate = (DateTime)date;
                });
            }
            catch (Exception exception)
            {

            }
        }

        private async void SubmitButton_OnClicked(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(birthDayEntry.Text) || string.IsNullOrEmpty((string)detailEntry.SelectedItem))
            {
                PopUpUtilites.ErrorPage("لطفا تمامی مقادیر را پر کنید");
                return;
            }

            birthdate.AddHours(4);
            var birthDate = new UserBirthDate
            {
                BirthDate = DateTime.Now,
                BirthDateString = birthdate.ToString(),
                Detail = detailEntry.SelectedItem as string
            };
            try
            {
                PopupNavigation.Instance.PushAsync(PopUpUtilites.IndicatorPage);
                RestService<ProfileRoot> restService = new RestService<ProfileRoot>(Address.BaseAddress);
                var res = await restService.RequestBody($"{Address.AddBirthDate}", Method.POST,birthDate, true);
                if (res.IsSuccess)
                {
                    PopupNavigation.Instance.PopAllAsync();
                    PopUpUtilites.SeccussPage("تاریخ با موفقیت افزوده شد");
                    Added.Invoke(this,new EventArgs());
                }
            }
            catch (Exception exception)
            {
                PopupNavigation.Instance.PopAllAsync();
                PopUpUtilites.ErrorPage(exception.Message);
            }
        }
    }
}