using Http.Core.Exceptions;
using Http.Core.Extensions;
using Http.Core;
using PCUT.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using static Http.Core.Constants.HttpConstants;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace PCUT.Pages.BannerManagement
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class BannerPage : Page
    {
        public BannerViewModel ViewModels { get; set; }

        public BannerPage()
        {
            this.InitializeComponent();
            ViewModels = DataContext as BannerViewModel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ViewModels.Pagination.Page = 1;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            ViewModels.Pagination.Dispose();
        }

        private async void AddBanner_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new BannerUpsertDialog();
            var result = await dialog.ShowAsync();
            if (result == ContentDialogResult.Primary)
                await ViewModels.Reload();
        }

        private async void EditBanner_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.CommandParameter is string bannerId)
            {
                if (CanEdit())
                {
                    var dialog = new BannerUpsertDialog(bannerId);
                    var result = await dialog.ShowAsync();
                    if (result == ContentDialogResult.Primary)
                        await ViewModels.Reload();
                    _editFlag = false;
                }
            }
        }

        private static readonly object _editLock = new object();
        private static bool _editFlag = false;
        private bool CanEdit()
        {
            if (!Monitor.TryEnter(_editLock))
                return false;

            try
            {
                if (_editFlag)
                    return false;

                _editFlag = true;
                return true;
            }
            finally
            {
                Monitor.Exit(_editLock);
            }
        }

        private async void DeleteBanner_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.CommandParameter is string bannerId)
            {
                if (CanDelete())
                {
                    //Confirm diaglog before delete
                    ContentDialog deleteDialog = new ContentDialog
                    {
                        Title = "Confirm Delete?",
                        Content = "Are you sure want delete this banner?",
                        PrimaryButtonText = "Delete",
                        CloseButtonText = "Cancel"
                    };
                    deleteDialog.PrimaryButtonStyle = Application.Current.Resources["PrimaryDialogButton"] as Style;
                    deleteDialog.CloseButtonStyle = Application.Current.Resources["CloseDialogButton"] as Style;

                    var result = await deleteDialog.ShowAsync();
                    if (result == ContentDialogResult.Primary)
                    {
                        await DeleteBannerAsync(bannerId);
                    }
                    _deleteFlag = false;
                }
            }
        }

        private static readonly object _deleteLock = new object();
        private static bool _deleteFlag = false;
        private bool CanDelete()
        {
            if (!Monitor.TryEnter(_deleteLock))
                return false;

            try
            {
                if (_deleteFlag)
                    return false;

                _deleteFlag = true;
                return true;
            }
            finally
            {
                Monitor.Exit(_deleteLock);
            }
        }

        private async Task DeleteBannerAsync(string bannerId)
        {
            using (var httpClient = HttpClientFactory.CreateClient(ClientNames.ApiClient))
            {
                try
                {
                    var response = await httpClient.DeleteAsync(Api.BannerById.FormatRoute(bannerId));
                    if (response.IsSuccessStatusCode)
                    {
                        await ShowDialog("Delete Success", "Banner Deleted!");
                        await ViewModels.Reload();
                    }
                    else
                    {
                        await ShowDialog("Error!", "Can't delete banner");
                    }
                }
                catch (Exception ex) when (!(ex is AppOutdatedException))
                {
                    await ShowDialog("Error!", $"Got exception: {ex.Message}");
                }
            }
        }


        private async Task ShowDialog(string title, string content)
        {
            ContentDialog dialog = new ContentDialog
            {
                Title = title,
                Content = content,
                CloseButtonText = "OK"
            };
            dialog.CloseButtonStyle = Application.Current.Resources["CloseDialogButton"] as Style;

            await dialog.ShowAsync();
        }

        private void btnFirst_Click(object sender, RoutedEventArgs e)
        {
            ViewModels.Pagination.Page = 1;
        }

        private void btnLast_Click(object sender, RoutedEventArgs e)
        {
            ViewModels.Pagination.Page = ViewModels.Pagination.TotalPage;
        }

        private void btnPrevious_Click(object sender, RoutedEventArgs e)
        {
            ViewModels.Pagination.Page--;
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            ViewModels.Pagination.Page++;
        }
    }
}
