#include "../include/Meteorite.h"
#include <algorithm>

namespace warfactory {

Meteorite::Meteorite(const json& meteorite_data) {
    meteorite_type = meteorite_data.at("type").get<std::string>();
    mass = meteorite_data.at("mass").get<float>();
    impact_energy_multiplier = meteorite_data.at("impact_energy_multiplier").get<float>();
    crater_formation_factor = meteorite_data.at("crater_formation_factor").get<float>();
    surface_metal_deposit_ratio = meteorite_data.at("surface_metal_deposit_ratio").get<float>();

    // Load resource composition
    if (meteorite_data.contains("resource_composition")) {
        const json& composition_data = meteorite_data.at("resource_composition");
        for (json::const_iterator it = composition_data.begin(); it != composition_data.end(); ++it) {
            resource_composition[it.key()] = it.value().get<float>();
        }
    }
}

float Meteorite::getResourceQuantity(const std::string& resource_id) const {
    const std::unordered_map<std::string, float>::const_iterator it = resource_composition.find(resource_id);
    return (it != resource_composition.end()) ? it->second : 0.0f;
}

bool Meteorite::hasResource(const std::string& resource_id) const {
    return resource_composition.find(resource_id) != resource_composition.end();
}

Meteorite Meteorite::copy() const {
    Meteorite copied;
    copied.meteorite_type = meteorite_type;
    copied.resource_composition = resource_composition;
    copied.mass = mass;
    copied.impact_energy_multiplier = impact_energy_multiplier;
    copied.crater_formation_factor = crater_formation_factor;
    copied.surface_metal_deposit_ratio = surface_metal_deposit_ratio;
    return copied;
}

Meteorite Meteorite::loadFromJson(const std::string& meteorite_type, const json& meteorite_data) {
    json complete_data = meteorite_data;
    complete_data["type"] = meteorite_type;
    return Meteorite(complete_data);
}

} // namespace warfactory