using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DiplomovaPrace.Web.Admin.Services;
using DiplomovaPrace.Web.Admin.Store.ProductCategoryUseCase;
using Fluxor;
using Microsoft.AspNetCore.Components;

namespace DiplomovaPrace.Web.Admin.Shared.Common
{
	public partial class ProductCategorySelect : ComponentBase
	{
		[Inject]
		private IProductCategoryService ProductCategoryService { get; set; }

		[Inject]
		private IState<ProductCategoryState> ProductCategoryState { get; set; }

		[Parameter]
		public int? Value { get; set; }

		[Parameter]
		public string DefaultValueText { get; set; }

		[Parameter]
		public EventCallback<int?> ValueChanged { get; set; }

		protected override async Task OnInitializedAsync()
		{
			await base.OnInitializedAsync();
			await ProductCategoryService.RequestProductCategoriesAsync();
		}

		protected override async Task OnParametersSetAsync()
		{
			Value ??= 0;
			await base.OnParametersSetAsync();
		}

		private async Task OnCategoryChange(ChangeEventArgs args)
		{
			if (int.TryParse(args.Value.ToString(), out int id))
			{
				Value = id != 0 ? id : null;
			}

			await ValueChanged.InvokeAsync(Value);
		}

		private List<string> GetAllParents(int parentID)
		{
			List<string> parents = new();

			if (parentID != -1)
			{
				var parent = ProductCategoryState.Value.ProductCategories.FirstOrDefault(i => i.ID == parentID);
				parents.Add(parent?.Name);

				if (parent != null && parent.ParentID != -1)
				{
					GetAllParents((int)parent.ParentID, ref parents);
				}
			}

			return parents;
		}

		private void GetAllParents(int parentID, ref List<string> parents)
		{
			var parent = ProductCategoryState.Value.ProductCategories.FirstOrDefault(i => i.ID == parentID);
			parents.Add($", {parent.Name}");

			if (parent.ParentID != -1)
			{
				GetAllParents((int)parent.ParentID, ref parents);
			}
		}
	}
}
