using System.Linq;
using DiplomovaPrace.Contracts.ProductCategories.ViewModels;
using DiplomovaPrace.Web.Admin.Store.ProductCategoryUseCase.Actions;
using Fluxor;

namespace DiplomovaPrace.Web.Admin.Store.ProductCategoryUseCase
{
	public static class Reducers
	{
		[ReducerMethod]
		public static ProductCategoryState RequestProductCategoriesAction(ProductCategoryState state, RequestProductCategoriesAction action) =>
			new ProductCategoryState(
				isLoading: true,
				productCategories: null);

		[ReducerMethod]
		public static ProductCategoryState ReceiveProductCategoriesAction(ProductCategoryState state, ReceiveProductCategoriesAction action) =>
			new ProductCategoryState(
				isLoading: false,
				productCategories: action.ProductCategories);

		[ReducerMethod]
		public static ProductCategoryState CreateProductCategoryAction(ProductCategoryState state, CreateProductCategoryAction action)
		{
			state.ProductCategories.Add(action.ProductCategory);

			return new ProductCategoryState(
				isLoading: state.IsLoading,
				productCategories: state.ProductCategories);
		}

		[ReducerMethod]
		public static ProductCategoryState UpdateProductCategoryAction(ProductCategoryState state, UpdateProductCategoryAction action)
		{
			foreach (ProductCategoryDto productCategory in state.ProductCategories.Where(i => i.ID == action.ProductCategoryID))
			{
				productCategory.Name = action.ProductCategory.Name;
				productCategory.Description = action.ProductCategory.Description;
				productCategory.ParentID = action.ProductCategory.ParentID;
			}

			return new ProductCategoryState(
				isLoading: state.IsLoading,
				productCategories: state.ProductCategories);
		}

		[ReducerMethod]
		public static ProductCategoryState DeleteProductCategoryAction(ProductCategoryState state, DeleteProductCategoryAction action)
		{
			foreach (int categoryID in action.ProductCategoryIDs)
			{
				state.ProductCategories.RemoveAll(i => i.ID == categoryID);
			}

			return new ProductCategoryState(
				isLoading: state.IsLoading,
				productCategories: state.ProductCategories);
		}
	}
}
