using PCUT.Entities;
using PCUT.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Http.Core;
using Http.Core.Extensions;
using static Http.Core.Constants.HttpConstants;
using Http.Core.Exceptions;
using PCUT.Entities.ApiResponse;
using Windows.ApplicationModel.Core;

namespace PCUT.ViewModels
{
    public class BannerViewModel : NotificationBase
    {
        public PaginationViewModel Pagination { get; } = new PaginationViewModel(withSearch: true);
        public SelectableCollection<BannerModel> FilteredBanners { get; } = new SelectableCollection<BannerModel>();

        public BannerViewModel()
        {
            Pagination.TextSearched += async (sender, args) => await SearchBannerAsync(args.Text);
            Pagination.PageChanged += OnPageChanged;
        }

        public async Task Reload()
        {
            await LoadBannerAsync(Pagination.Page, Pagination.PageSize, Pagination.SearchText);
        }

        private async void OnPageChanged(object sender, PageChangedEventArgs args)
        {
            await LoadBannerAsync(args.Page, args.PageSize, Pagination.SearchText);
        }

        private async Task SearchBannerAsync(string searchText)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                await LoadBannerAsync(Pagination.Page, Pagination.PageSize, searchText);
            });
        }

        private async Task LoadBannerAsync(int page, int pageSize, string searchText)
        {
            var url = CreateFilterUrl(page, pageSize, searchText);
            using (var httpClient = HttpClientFactory.CreateClient(ClientNames.ApiClient))
            {
                try
                {
                    var response = await httpClient.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        var apiResponse = await response.DeserializeObjectAsync<PaginationResponse<IEnumerable<BannerModel>>>();
                        var data = apiResponse.Data;
                        Pagination.Page = apiResponse.Pagination.Page;
                        Pagination.TotalPage = apiResponse.Pagination.TotalPages;
                        Pagination.TotalRecords = apiResponse.Pagination.TotalRecords;

                        int displayId = (apiResponse.Pagination.Page - 1) * pageSize + 1;
                        var banners = data.Select(banner =>
                        {
                            banner.DisplayId = displayId.ToString();
                            displayId++;
                            return banner;
                        });
                        FilteredBanners.Load(banners);
                    }
                }
                catch (Exception ex) when (!(ex is AppOutdatedException))
                {
                }
            }
        }

        private string CreateFilterUrl(int page, int pageSize, string searchText)
        {
            var builder = PathBuilder.FromRouteTemplate(Api.Banner)
                                     .AddQuery("page", page.ToString())
                                     .AddQuery("pageSize", pageSize.ToString());
            if (!string.IsNullOrEmpty(searchText))
            {
                var filter = new StringBuilder().AppendFilter("name", "cn", searchText).BuildFilter().ToString();
                builder.AddQuery("filter", filter);
            }
            return builder.Build();
        }

        public class BannerModel : Banner
        {
            public string DisplayId { get; set; }
        }
    }
}
