using System;
using BlazorApp.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using BlazorApp.Services;
using Blazorise.DataGrid;

namespace BlazorApp.Components
{
    public partial class InventoryComp
    {

        public Item CurrentDragItem { get; set; }

        public int CurrentDragIndex { get; set; }

        [Inject]
        public IDataService DataService { get; set; }

        [Parameter]
        public List<Item> Items { get; set; }

        public List<Item> InventoryItems { get; set; }

        public ObservableCollection<CraftingAction> Actions { get; set; }

        [Inject]
        internal IJSRuntime JavaScriptRuntime { get; set; }

        private int totalItem;

        public bool IsSorted { get; set; }

        private int PageSize { get; set; }

        private int CurrentPage { get; set; }


        public InventoryComp()
        {
            Actions = new ObservableCollection<CraftingAction>();

            Actions.CollectionChanged += OnActionsCollectionChanged;

            this.InventoryItems = new List<Item>(new Item[18]);
        }

        private void OnActionsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
        {
            JavaScriptRuntime.InvokeVoidAsync("Crafting.AddActions", e.NewItems);
        }

        private async Task OnReadData(DataGridReadDataEventArgs<Item> e)
        {
            if (e.CancellationToken.IsCancellationRequested)
            {
                return;
            }
            if (!e.CancellationToken.IsCancellationRequested && !IsSorted)
            {
                Items = await DataService.List(e.Page, e.PageSize);
                totalItem = await DataService.Count();
                CurrentPage = e.Page;
                PageSize = e.PageSize;
            }
            else
            {
                CurrentPage = e.Page;
                PageSize = e.PageSize;
                Items = await DataService.SortedList(CurrentPage, PageSize);
            }
        }

        private async Task SortByName()
        {
            if (!IsSorted)
            {
                IsSorted = true;
                Items = await DataService.SortedList(CurrentPage, PageSize);
            }
        }

        void refresh()
        {
            StateHasChanged();
        }

    }
}