using Blazorise.DataGrid;
using ValblazeProject.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using ValblazeProject.Services;
using ValblazeProject.Components;
using System.Collections.ObjectModel;
using Microsoft.JSInterop;
using System.Collections.Specialized;
using System.Text.Json;

namespace ValblazeProject.Pages
{
    public partial class Inventaire
    {
        /******************* Initialisation des attributs *******************/
        /// <summary>
        /// Pour traduire la page
        /// </summary>
        [Inject]
        public IStringLocalizer<List> Localizer { get; set; }

        /// <summary>
        /// Data de l'API
        /// </summary>
        [Inject]
        public IDataService DataService { get; set; }

        /// <summary>
        /// Gets or sets the java script runtime.
        /// </summary>
        [Inject]
        internal IJSRuntime JavaScriptRuntime { get; set; }

        /// <summary>
        /// Ma liste d'Item
        /// </summary>
        public List<Item> items { get; set; } = new List<Item>();

        /// <summary>
        /// List inventaire sauvegarder
        /// </summary>
        public List<Item> InventoryItems;

        /// <summary>
        /// Donnée de la Grid Blazorise
        /// </summary>
        private DataGrid<Item> dataGrid;

        /// <summary>
        /// Liste des actions
        /// </summary>
        public ObservableCollection<InventoryAction> Actions { get; set; }

        /// <summary>
        /// Item selectionner lors d'un glisser déposer
        /// </summary>
        public Item CurrentDragItem { get; set; }

        private int totalItem;
        private string _searchText;
        private int totalSizeByPage = 5;
        private bool _trie = false;
          
        /******************* Attribut modifier *******************/
        private string search
        {
            get { return _searchText; }
            set
            {
                if(_searchText != value )
                {
                    _searchText = value;
                    SearchTextChange();
                }               
            }
        }

        private bool trieActive
        {
            get { return _trie; }
            set
            {
                if (_trie != value)
                {
                    _trie = value;
                    TrieChanged();
                }
            }
        }

        /******************* Méthodes *******************/
        /// <summary>
        /// Constructeur
        /// </summary>
        public Inventaire()
        {
            Actions = new ObservableCollection<InventoryAction>();
            Actions.CollectionChanged += OnActionsCollectionChanged;

            string fileName = "Inventory.json";
            string jsonString = File.ReadAllText(fileName);
            this.InventoryItems = JsonSerializer.Deserialize<List<Item>>(jsonString)!;
        }

        /// <summary>
        /// Trie par ordre alphabétique 
        /// </summary>
        /// <returns></returns>
        public async Task TrieChanged()
        {
            await dataGrid.Reload();
            StateHasChanged();
        }

        /// <summary>
        /// Méthode de recherche
        /// </summary>
        /// <returns></returns>
        public async Task SearchTextChange()
        {
            dataGrid.CurrentPage = 1;
            await dataGrid.Reload();
            StateHasChanged();
        }

        /// <summary>
        /// Initialisation des données via un service
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        private async Task OnReadData(DataGridReadDataEventArgs<Item> e)
        {
            if (e.CancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (!e.CancellationToken.IsCancellationRequested)
            {
                items = await DataService.List();

                // Search
                if (!string.IsNullOrEmpty(_searchText))
                {
                    items = items.Where(i => i.DisplayName.Contains(_searchText)).ToList();
                }

                // Trie
                if (_trie)
                {
                    items = items.OrderBy(i => i.DisplayName).ToList();
                    Actions.Add(new InventoryAction { Action = "Sort by Name" });
                }

                // Gestion pagination
                totalItem = items.Count;
                int pageCourante = dataGrid.CurrentPage;
                items = items.Skip((pageCourante - 1) * totalSizeByPage).Take(totalSizeByPage).ToList();
                StateHasChanged();
            }
        }

        /// <summary>
        /// method that call the javascript 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnActionsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
        {
            // je fais appel au fichier js de crafting, car je n'ai pas su résoudre le problème avec celui Inventaire.razor.js
            JavaScriptRuntime.InvokeVoidAsync("Crafting.AddActions", e.NewItems);
        }
    }
}
