using Blazored.LocalStorage;
using Blazored.Modal;
using Blazored.Modal.Services;
using Blazorise.DataGrid;
using ValblazeProject.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using ValblazeProject.Modals;
using ValblazeProject.Services;
using ValblazeProject.Components;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Microsoft.AspNetCore.Components.Forms;
using System.Linq;
using Microsoft.JSInterop;
using System.Collections.Specialized;
using Microsoft.AspNetCore.Components.Web;

namespace ValblazeProject.Pages
{
    public partial class Inventaire
    {
        /******************* Initialisation des attributs *******************/
        private List<Item> items;
        private int totalItem;

        [Inject]
        public IStringLocalizer<List> Localizer { get; set; }

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

        [Inject]
        public IWebHostEnvironment WebHostEnvironment { get; set; }

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

        [CascadingParameter]
        public IModalService Modal { get; set; }

        private DataGrid<Item> dataGrid;
        private string _searchText;
        private int totalSizeByPage = 10;
        private bool _trie = false;


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

        public Item CurrentDragItem { get; set; }

        public Inventaire()
        {
            Actions = new ObservableCollection<CraftingAction>();
            Actions.CollectionChanged += OnActionsCollectionChanged;
        }

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

        // Drag

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            base.OnAfterRenderAsync(firstRender);

            if (!firstRender)
            {
                return;
            }

            StateHasChanged();
        }

        public void OnDragEnter()
        {
            Drag.OnDragEnter();
        }
        public void OnDragStart()
        {
            Drag.OnDragStart();
        }
        public void OnDrop()
        {
            Drag.OnDrop();
        }
        public void OnDragLeave()
        {
            Drag.OnDragLeave();
        }

        private CraftingItem Drag;
        

        /******************* 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>
        /// 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)
            {
                /* Il est important de découper le processus en 3 étapes: 
                    1. le filtre
                    2. le tri
                    3. la pagination
                */

                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();
                }

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

  /*      private async void OnDelete(int id)
        {
            var parameters = new ModalParameters();
            parameters.Add(nameof(Item.Id), id);

            var modal = Modal.Show<DeleteConfirmation>("Delete Confirmation", parameters);
            var result = await modal.Result;

            if (result.Cancelled)
            {
                return;
            }

            await DataService.Delete(id);

            // Reload the page
            NavigationManager.NavigateTo("list", true);
        }*/
    }
}
