using CareFusion.Mosaic.Converters.Wwks2.Types;
using CareFusion.Mosaic.Interfaces.Converters;
using CareFusion.Mosaic.Interfaces.Messages.Stock;
using CareFusion.Mosaic.Interfaces.Types.Packs;
using StorageSystemSimulator;
using System;
using System.Collections.Generic;

namespace StorageSystem.Simulator.Cores.StockUpdateHandler;

internal class AccordingToStockHandler : StockUpdateHandlerBase
{
    private readonly StorageSystemStock _stock;
    private readonly Action<RobotPack> _onUpdatedPack;

    public AccordingToStockHandler(StorageSystemStock stock,
        Action<RobotPack> onUpdatedPack,
        List<IConverterStream> converterStreams
    ) : base(converterStreams)
    {
        _stock = stock;
        _onUpdatedPack = onUpdatedPack;
    }

    protected override void FillResponse(StockUpdateRequest request, StockUpdateResponse response)
    {
        var updated = 0;
        _stock.ArticleInformationList.ArticlesAsList.ForEach(article =>
        {
            foreach (var criterion in request.Criteria)
            {
                StockProduct product = null;
                if (string.IsNullOrWhiteSpace(criterion.ArticleId))
                {
                    product = _stock.GetStockProduct(article.Code);

                }
                else if (article.Code == criterion.ArticleId)
                {
                    product = _stock.GetStockProduct(article.Code);

                }

                if (product is null) continue;

                var packs = product.GetPackList(criterion.BatchNumber, criterion.ExternalId, criterion.MachineLocation,
                    criterion.StockLocationId, long.Parse(criterion.PackId ?? "0"), null);

                packs.ForEach(x =>
                {
                    x.BatchNumber = request.Pack?.BatchNumber;
                    _onUpdatedPack(x);
                });
                updated += packs.Count;
            }
        });

        if (updated > 0)
        {
            response.Details = new Details
            {
                Status = "Accepted"
            };
        }
        else
        {
            response.Details = new Details
            {
                Status = "Rejected",
                Reason = "No pack on stock matches update criterias"
            };
        }
    }


}