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

namespace BlazorApp.Components
{
    public partial class InventoryComponent
    {
        [Inject]
        public IStringLocalizer<List> Localizer { get; set; }
        [Inject]
        public IDataService DataService { get; set; }

        private int totalItem;

        public Item CurrentDragItem { get; set; }
        public int CurrentDragItemIndex { get; set; }

        private bool choiceSort = false;
        public List<Item> RecipeItems { get; set; }

        [Parameter]
        public List<Item> Items { get; set; } = new List<Item>();
        public ObservableCollection<InventoryAction> Actions { get; set; }

        [Inject]
        internal IJSRuntime JavaScriptRuntime { get; set; }
        /// <summary>
        /// Constructor
        /// </summary>
        public InventoryComponent()
        {
            Actions = new ObservableCollection<InventoryAction>();
            Actions.CollectionChanged += OnActionsCollectionChanged;

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

        /// <summary>
        /// method that call the javascript 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnActionsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
        {
            JavaScriptRuntime.InvokeVoidAsync("Crafting.AddActions", e.NewItems);


         
        }

        /// <summary>
        /// method to sort by name or id simultaneoustly
        /// </summary>
        private void SortByame()
        {
            if (choiceSort)
            {
                Items.Sort((x, y) => x.Id.CompareTo(y.Id));
                choiceSort = !choiceSort;
                Actions.Add(new InventoryAction { Action = "Sort by Id" });
            }
            else
            {
                Items.Sort((x, y) => x.Name.CompareTo(y.Name));
                choiceSort = !choiceSort;
                Actions.Add(new InventoryAction { Action = "Sort by Name" });
            }
        }

    }
}
