#include "client/gui/BaseGUI.h"

static const Color4 INPUT_BACKGROUND(0xFF, 0xFF, 0xFF, 0x80);
static const Color4 INPUT_BACKGROUND_2(0xFF, 0xFF, 0xFF, 0xC0);
const Vector2 BaseGUI::FIXED_SIZE(400.0f, 300.0f);

BaseGUI::BaseGUI(const Size& size, TextInput*& textInput,
                 const Controller& controller)
    : size(size), textInput(textInput), controller(controller) {
}

void BaseGUI::tick() {
    if(controller.leftClick.wasReleased()) {
        Vector2 mousePos = controller.getMouse() / scale;
        for(Input& input : inputs) {
            if(isIn(input.pos, input.size, mousePos)) {
                textInput = &input.text;
                textInput->setActive(true);
                break;
            }
        }
    }
}

void BaseGUI::updateScale(ShaderMatrix& sm) {
    scale = static_cast<int>(
        std::min(size.width / FIXED_SIZE[0], size.height / FIXED_SIZE[1]));
    scale = scale < 1.0f ? 1.0f : scale;
    scaledSize = Vector2(size.width / scale, size.height / scale);
    sm.scale(scale).update();
}

void BaseGUI::render(float lag, ShaderMatrix& sm, Renderer& r) {
    (void)lag;
    (void)sm;

    Vector2 mousePos = controller.getMouse() / scale;
    for(Input& input : inputs) {
        if(isIn(input.pos, input.size, mousePos)) {
            r.drawRectangle(input.pos, input.size, INPUT_BACKGROUND_2);
        } else {
            r.drawRectangle(input.pos, input.size, INPUT_BACKGROUND);
        }
        StringBuffer<256> text(input.text);
        r.drawString(input.pos[0], input.pos[1], text);
    }
    r.drawString(0, 50, StringBuffer<50>(controller.getMouse()));
}

float BaseGUI::round(float f) const {
    return static_cast<int>(f * scale) / scale;
}

void BaseGUI::drawCenteredString(Renderer& r, float x, float y, const char* s) {
    r.drawString(round(x - r.drawStringWidth(s) * 0.5f), round(y), s);
}

BaseGUI::Input& BaseGUI::addInput() {
    inputs.add();
    return inputs[inputs.getLength() - 1];
}

bool BaseGUI::isIn(const Vector2& pos, const Vector2& size,
                   const Vector2& point) const {
    Vector2 end = pos + size;
    return pos[0] <= point[0] && point[0] <= end[0] && pos[1] <= point[1] &&
           point[1] <= end[1];
}