package fyloz.trial.ColorRecipesExplorer.services;

import fyloz.trial.ColorRecipesExplorer.model.Material;
import fyloz.trial.ColorRecipesExplorer.model.Mix;
import fyloz.trial.ColorRecipesExplorer.model.MixQuantity;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.stream.Collectors;

@Service
public class InventoryService {

    private MaterialService materialService;

    public InventoryService(MaterialService materialService) {
        this.materialService = materialService;
    }

    public String checkQuantities(Mix mix, Map<Material, Float> quantities) {
        for (Material material : mix.getMixQuantities().stream().map(MixQuantity::getMaterial).collect(Collectors.toList())) {
            if (!material.isMixType()) {
                float quantity = quantities.get(material);

                if (quantity > material.getInventoryQuantity()) {
                    return String.format("%s-%s", mix.getMixID(), material.getMaterialID());
                }
            }
        }

        return null;
    }

    public boolean useMix(Mix mix, Map<Material, Float> quantities) {
        for (Material material : mix.getMixQuantities().stream().map(MixQuantity::getMaterial).collect(Collectors.toList())) {
            if (!material.isMixType()) {
                float quantity = quantities.get(material);

                material.setInventoryQuantity(material.getInventoryQuantity() - quantity);
                if (materialService.update(material) == null) return false;
            }
        }

        return true;
    }
}
