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

namespace PCUT.ViewModels
{
    public class UserViewModel : NotificationBase
    {
        public PaginationViewModel Pagination { get; } = new PaginationViewModel(withSearch: true);
        public SelectableCollection<UsersModel> FilteredUsers { get; }
        public UserViewModel()
        {
            FilteredUsers = new SelectableCollection<UsersModel>();

            Pagination.TextSearched += async (sender, args) => await SearchCategoryAsync(args.Text);
            Pagination.PageChanged += OnPageChanged;
        }

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

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

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

        public async Task LoadUserAsync(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<UsersModel>>>();
                        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 users = data.Select(user =>
                        {
                            user.DisplayId = displayId.ToString();
                            displayId++;
                            return user;
                        });
                        FilteredUsers.Load(users);
                    }
                }
                catch (Exception ex) when (!(ex is AppOutdatedException))
                {
                   
                }
            }
        }

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