#pragma once

#include <string>

#include "application/config/values/TypedConfigValue.h"
#include "foundation/input/KeyNames.h"

namespace ta::application::config
{
class KeybindValue final : public TypedConfigValue<int>
{
public:
    KeybindValue(const int initial, const std::string& name, const bool allow_none = true)
        : TypedConfigValue(normalize(initial, allow_none), name), allow_none_(allow_none) {}

    [[nodiscard]] ConfigValueKind kind() const override { return ConfigValueKind::Keybind; }
    [[nodiscard]] bool allow_none() const noexcept { return allow_none_; }

protected:
    [[nodiscard]] ApplyError assign_typed(const int& value) override
    {
        if ((!allow_none_ && value == 0) ||
            (value != 0 && !ta::foundation::input::is_valid_key_index(value)))
        {
            return ApplyError::InvalidValue;
        }
        store(value);
        return ApplyError::None;
    }

private:
    bool allow_none_ = true;

    static int normalize(const int value, const bool allow_none) noexcept
    {
        if (allow_none && value == 0)
            return 0;
        return ta::foundation::input::is_valid_key_index(value) ? value : (allow_none ? 0 : 0x2D);
    }
};
}
