#include "application/config/ConfigRegistry.h"

#include <stdexcept>

namespace ta::application::config
{
    ConfigRegistry::ConfigRegistry(ConfigOwner& global_config, const std::span<ConfigOwner* const> owners)
        : global_config_(global_config), owners_(owners.begin(), owners.end())
    {
        index_owner(global_config_);
        for (ConfigOwner* owner : owners_)
        {
            if (owner)
                index_owner(*owner);
        }
    }

    void ConfigRegistry::index_owner(ConfigOwner& owner)
    {
        for (ConfigValue* value : owner.config_values())
        {
            if (!value || value->get_config_key().empty())
                throw std::logic_error("unregistered config value in owner: " + owner.config_owner_id());
            if (!values_by_key_.emplace(value->get_config_key(), value).second)
                throw std::logic_error("duplicate config key: " + value->get_config_key());
            value->bind_revision(revision_);
            values_.push_back(value);
        }


        for (ta::application::UiAction* action : owner.ui_actions())
        {
            if (!action || action->key().empty())
                continue;
            if (!actions_by_key_.emplace(action->key(), action).second)
                throw std::logic_error("duplicate UI action key: " + action->key());
        }
    }


    ConfigValue* ConfigRegistry::find_value(const std::string_view key) const noexcept
    {
        if (const auto found = values_by_key_.find(std::string(key)); found != values_by_key_.end())
            return found->second;
        return nullptr;
    }

    ta::application::UiAction* ConfigRegistry::find_action(const std::string_view key) const noexcept
    {
        if (const auto found = actions_by_key_.find(std::string(key)); found != actions_by_key_.end())
            return found->second;
        return nullptr;
    }
}
