#include "item_db.hpp"

ItemDB::StaticData::~StaticData() {
    if(this->hint != nullptr)
        delete this->hint;
    if(this->array_hint != nullptr)
        delete this->array_hint;
    for(Item *action : this->items)
        delete action;
}

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

gd::String &ItemDB::StaticData::get_array_hint() {
    if(this->array_hint == nullptr)
        this->array_hint = new gd::String("None");
    return *this->array_hint;
}

ItemID ItemDB::register_item(Item *item, gd::String item_name) {
    item->id = ItemDB::data.items.size()+1;
    ItemDB::data.get_hint() += ",";
    ItemDB::data.get_hint() += item_name;
    ItemDB::data.get_array_hint() = gd::vformat("%s/%s:%s", gd::Variant::INT, gd::PROPERTY_HINT_ENUM, ItemDB::data.get_hint());
    ItemDB::data.items.push_back(item);
    return item->get_id();
}

Item const *ItemDB::get_item(ItemID index) {
    index -= 1;
    if(ItemDB::data.items.size() <= index || index < 0) {
        gd::UtilityFunctions::push_warning("Attempted to get pointer to non-existent item type by ID ", index);
        return nullptr;
    }
    return ItemDB::data.items[index];
}

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

gd::String const &ItemDB::get_array_hint() {
    return ItemDB::data.get_array_hint();
}

Item const *ItemDB::get_item_by_name(gd::StringName item_name) {
    for(Item const *item : ItemDB::data.items)
        if(item->get_class() == item_name)
            return item;
    return nullptr;
}

ItemDB::StaticData ItemDB::data{};
