#include "CommandMap.h"
#include "Command.h"

CommandMap::CommandMap()
{
    m_commands[0] = m_commands[1] = Command::NOP;
}

std::shared_ptr<CommandMap> CommandMap::access(uint32_t entry, bool insert)
{
    auto it = m_children.find(entry);
    if (it == m_children.end())
    {
        if (insert)
        {
            std::shared_ptr<CommandMap> new_cm = std::make_shared<CommandMap>();
            m_children[entry] = new_cm;
            return new_cm;
        }
        else
        {
            return nullptr;
        }
    }
    return it->second;
}

std::shared_ptr<CommandMap> CommandMap::access(const std::vector<uint32_t> entries, bool insert)
{
    if (entries.size() == 0u)
    {
        return nullptr;
    }
    std::shared_ptr<CommandMap> cm = access(entries[0], insert);
    for (size_t i = 1u; i < entries.size(); i++)
    {
        if (cm == nullptr)
        {
            break;
        }
        cm = cm->access(entries[i], insert);
    }
    return cm;
}

uint32_t CommandMap::command() const
{
    if (m_commands[1] != Command::NOP)
    {
        return m_commands[1];
    }
    return m_commands[0];
}

void CommandMap::set_command(uint32_t command, bool user_mapping)
{
    m_commands[user_mapping ? 1 : 0] = command;
}

bool CommandMap::empty() const
{
    return (m_commands[0] == Command::NOP) &&
        (m_commands[1] == Command::NOP) &&
        (m_children.size() == 0u);
}
