#include "client/Game.h"
#include "gaming-core/utils/Utils.h"

Game::Game(const Controller& controller, const Clock& fps, const Clock& tps, RenderSettings& settings, const Size& size)
    : controller(controller), fps(fps), tps(tps), renderSettings(settings), size(size), world(blockRegistry),
      worldRenderer(world) {
    pos = Vector3(16.0f, 30.0f, -10.0f);
    rotation = Quaternion(Vector3(1.0f, 0.0f, 0.0f), 30) * rotation;
    rotation = Quaternion(Vector3(0.0f, 1.0f, 0.0f), 30) * rotation;
}

void Game::tick() {
    lastRotation = rotation;
    lastPos = pos;

    Vector3 right = rotation * Vector3(1.0f, 0.0f, 0.0f);
    Vector3 up = rotation * Vector3(0.0f, 1.0f, 0.0f);
    Vector3 back = rotation * Vector3(0.0f, 0.0f, -1.0f);

    const float speed = 8.0f;
    if(controller.down.isDown()) {
        pos += back * speed;
    }
    if(controller.up.isDown()) {
        pos -= back * speed;
    }
    if(controller.left.isDown()) {
        pos -= right * speed;
    }
    if(controller.right.isDown()) {
        pos += right * speed;
    }
    if(controller.jump.isDown()) {
        pos += up * speed;
    }
    if(controller.sneak.isDown()) {
        pos -= up * speed;
    }

    const float rotationSpeed = 5.0f;
    if(controller.camLeft.isDown()) {
        rotation = Quaternion(up, -rotationSpeed) * rotation;
    }
    if(controller.camRight.isDown()) {
        rotation = Quaternion(up, rotationSpeed) * rotation;
    }
    if(controller.camUp.isDown()) {
        rotation = Quaternion(right, -rotationSpeed) * rotation;
    }
    if(controller.camDown.isDown()) {
        rotation = Quaternion(right, rotationSpeed) * rotation;
    }
}

void Game::renderWorld(float lag, Renderer& renderer) {
    renderer.update(Utils::interpolate(lastPos, pos, lag), lastRotation.lerp(lag, rotation));
    worldRenderer.render(lag, renderer);
}

void Game::renderTextOverlay(float lag, Renderer& renderer, FontRenderer& fr) {
    (void)lag;
    renderer.scale(2.0f).update();
    StringBuffer<100> s;
    s.append("FPS: &074").append(fps.getUpdatesPerSecond()).append(" &999TPS: &722").append(tps.getUpdatesPerSecond());
    fr.drawString(10, 10, s);
}

bool Game::isRunning() const {
    return true;
}