using System.Linq;
using DiplomovaPrace.Web.Admin.Store.ProductUseCase.Actions;
using Fluxor;

namespace DiplomovaPrace.Web.Admin.Store.ProductUseCase
{
	public static class Reducers
	{
		[ReducerMethod]
		public static ProductState RequestProductsAction(ProductState state, RequestProductsAction action) =>
			new ProductState(
				isLoading: true,
				products: null);

		[ReducerMethod]
		public static ProductState ReceiveProductsAction(ProductState state, ReceiveProductsAction action)
		{
			return new ProductState(
				isLoading: false,
				products: action.Products);
		}

		[ReducerMethod]
		public static ProductState CreateProductAction(ProductState state, CreateProductAction action)
		{
			state.Products.Add(action.Product);

			return new ProductState(
				isLoading: state.IsLoading,
				products: state.Products);
		}

		[ReducerMethod]
		public static ProductState UpdateProductAction(ProductState state, UpdateProductAction action)
		{
			foreach (var product in state.Products.Where(i => i.ID == action.ID))
			{
				product.Name = action.Product.Name;
				product.Price = action.Product.Price;
				product.ReducedPrice = action.Product.ReducedPrice;
				product.AvailableQuantity = action.Product.AvailableQuantity;
				product.Description = action.Product.Description;
				product.ProductCategoryID = action.Product.ProductCategoryID;
			}

			return new ProductState(
				isLoading: state.IsLoading,
				products: state.Products);
		}

		[ReducerMethod]
		public static ProductState DeleteProductAction(ProductState state, DeleteProductAction action)
		{
			state.Products.RemoveAll(i => i.ID == action.ID);

			// jestli bude problem, tak mozne reseni:
			//List<ProductDto> products = state.Products.Where(i => i.ID != action.ID).ToList();

			return new ProductState(
				isLoading: state.IsLoading,
				products: state.Products);
		}
	}
}
