using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Blazored.Toast.Services;
using DiplomovaPrace.Contracts.Products;
using DiplomovaPrace.Contracts.Products.InputModels;
using DiplomovaPrace.Contracts.Products.ViewModels;
using DiplomovaPrace.Web.Admin.Store.ProductUseCase.Actions;
using Fluxor;
using Microsoft.AspNetCore.Components;

namespace DiplomovaPrace.Web.Admin.Services
{
	public class ProductService : IProductService
	{
		private readonly IProductFacadeContract productFacadeContract;
		private readonly IDispatcher dispatcher;
		private readonly IToastService toastService;
		private readonly NavigationManager navigationManager;

		public ProductService(IProductFacadeContract productFacadeContract, IDispatcher dispatcher, IToastService toastService, NavigationManager navigationManager)
		{
			this.productFacadeContract = productFacadeContract;
			this.dispatcher = dispatcher;
			this.toastService = toastService;
			this.navigationManager = navigationManager;
		}

		private async Task<List<ProductDto>> ReceiveProductsInternalAsync()
		{
			return await productFacadeContract.GetAllProductsAsync().ConfigureAwait(false);
		}

		public async Task CreateProductAsync(ProductIM inputModel)
		{
			ProductDto product = await productFacadeContract.CreateProductAsync(inputModel).ConfigureAwait(false);

			// Celý data storage asi odebrat (je zbytečný)
			//if (product is not null)
			//{
			//	dispatcher.Dispatch(new CreateProductAction(product));
			//}

			navigationManager.NavigateTo("products");
			toastService.ShowSuccess("Produkt úspěšně vytvořen!", "POVEDLO SE");
		}

		public async Task<ProductDto> GetProductAsync(int productId)
		{
			return await productFacadeContract.GetProductAsync(new GetProductRequest { ID = productId }).ConfigureAwait(false);
		}

		public async Task RequestProductsAsync()
		{
			dispatcher.Dispatch(new RequestProductsAction());
			dispatcher.Dispatch(new ReceiveProductsAction(await ReceiveProductsInternalAsync().ConfigureAwait(true)));
		}

		public async Task UpdateProductAsync(ProductDto inputModel)
		{
			await productFacadeContract.UpdateProductAsync(inputModel).ConfigureAwait(false);

			//dispatcher.Dispatch(new UpdateProductAction(inputModel.ID, inputModel));

			navigationManager.NavigateTo("products");
			toastService.ShowSuccess("Produkt úspěšně upraven!", "POVEDLO SE");
		}

		public async Task<bool> DeleteProductAsync(int productId)
		{
			DeleteProductResult result = await productFacadeContract.DeleteProductAsync(new DeleteProductRequest { ID = productId }).ConfigureAwait(false);

			//dispatcher.Dispatch(new DeleteProductAction(id));

			return result.IsSuccessful;
		}

		public async Task<bool> DeleteProductImageAsync(int imageId)
		{
			DeleteProductImageResult result = await productFacadeContract.DeleteProductImageAsync(new DeleteProductImageRequest { ID = imageId }).ConfigureAwait(true);

			return result.IsSuccessful;
		}
	}
}
