#include <Widget/TextField/ChatTextField/ChatTextField.hpp>

ChatTextField::ChatTextField(std::string &text, Player &player, Uint32 &lastChangeTicks, std::function<void()> onAccept) :
    TextField(text, onAccept, false),
    fieldHistory(player.chatHistory),
    historyIndex(player.chatHistory.size()),
    lastChangeTicks(lastChangeTicks)
{
    withChangedCallback([this]()
    {
        this->lastChangeTicks = SDL_GetTicks();
    });
}

void ChatTextField::onKeyDown(SDL_Keycode keycode)
{
    if (historyIndex < 0)
    {
        historyIndex = 0;
    }
    
    TextField::onKeyDown(keycode);
    
    if (fieldHistory.size() > 0)
    {
        if (keycode == SDLK_UP && historyIndex - 1 >= 0)
        {
            historyIndex--;
            text = fieldHistory.at(historyIndex);
            selectStart = selectEnd = text.size();
        }
        else if (keycode == SDLK_DOWN && historyIndex + 1 < fieldHistory.size())
        {
            historyIndex++;
            text = fieldHistory.at(historyIndex);
            selectStart = selectEnd = text.size();
        }
        else if ((keycode == SDLK_DOWN || keycode == SDLK_UP) && historyIndex < fieldHistory.size())
        {
            text = fieldHistory.at(historyIndex);
            selectStart = selectEnd = text.size();
        }
    }
}