#include "ItemProducers.h"

#include "GameConfig.h"
#include "RecipesConfig.h"
#include "Simulation.h"

namespace
{

bool producesItem(const RecipeDef& recipe, const std::string& itemId)
{
    for (const RecipeOutput& output : recipe.outputs)
    {
        if (output.item == itemId)
        {
            return true;
        }
    }
    return false;
}

bool isAvailable(const RecipeDef& recipe, const Simulation& sim)
{
    if (recipe.building == BuildingType::Miner
        || recipe.building == BuildingType::Assembler)
    {
        return sim.isRecipeUnlocked(recipe.id);
    }
    return sim.isBuildingUnlocked(recipe.building);
}

}  // namespace

ItemProduction findItemProduction(const std::string& itemId, const Simulation& sim,
                                  const GameConfig& config)
{
    ItemProduction result;

    bool anyProducer = false;
    for (const RecipeDef& recipe : config.recipes.recipes)
    {
        if (!producesItem(recipe, itemId)) { continue; }

        anyProducer = true;
        if (isAvailable(recipe, sim))
        {
            result.recipes.push_back(&recipe);
        }
    }

    if (!result.recipes.empty())
    {
        result.origin = ItemOrigin::Produced;
    }
    else
    {
        result.origin = anyProducer ? ItemOrigin::Undiscovered : ItemOrigin::Salvaged;
    }
    return result;
}
