#include "action_db.hpp"
#include "godot_cpp/variant/utility_functions.hpp"

namespace goap {
ActionDB::StaticData::~StaticData() {
    if(this->hint != nullptr)
        delete this->hint;
    for(Action *action : this->actions)
        delete action;
}

gd::String &ActionDB::StaticData::get_hint() {
    if(this->hint == nullptr)
        this->hint = new gd::String();
    return *this->hint;
}

ActionID ActionDB::register_action(Action *instance, gd::String name) {
    instance->id = ActionDB::data.actions.size();
    if(!ActionDB::data.get_hint().is_empty())
        ActionDB::data.get_hint() += ",";
    ActionDB::data.get_hint() += name;
    // defer intialization until after emplacement to avoid deleting instance
    ActionDB::data.actions.push_back(instance);
    gd::UtilityFunctions::print("registered action ", name);
    return instance->get_id();
}

Action const *ActionDB::get_action(ActionID index) {
    if(ActionDB::data.actions.size() <= index || index < 0) {
        gd::UtilityFunctions::push_warning("Attempted to get pointer to non-existent Action by ActionID ", index);
        return nullptr;
    }
    return ActionDB::data.actions[index];
}

gd::String const &ActionDB::get_enum_hint() {
    return ActionDB::data.get_hint();
}

ActionDB::StaticData ActionDB::data{};
}
