#include "ingame.h"
#include "title.h"
#include "scene.h"

#include "twn_game_api.h"
#include "twn_vec.h"

#include <SDL2/SDL.h>


static void ingame_tick(State *state) {
    SceneIngame *scn = (SceneIngame *)state->scene;

    world_drawdef(scn->world);
    player_calc(scn->player);

    const Vec3 right = m_vec_norm(m_vec_cross(scn->cam.target, scn->cam.up));
    const float speed = 0.04f; /* TODO: put this in a better place */
    if (input_is_action_pressed("player_left"))
        scn->cam.pos = vec3_sub(scn->cam.pos, m_vec_scale(right, speed));

    if (input_is_action_pressed("player_right"))
        scn->cam.pos = vec3_add(scn->cam.pos, m_vec_scale(right, speed));

    if (input_is_action_pressed("player_forward"))
        scn->cam.pos = vec3_add(scn->cam.pos, m_vec_scale(scn->cam.target, speed));

    if (input_is_action_pressed("player_backward"))
        scn->cam.pos = vec3_sub(scn->cam.pos, m_vec_scale(scn->cam.target, speed));

    if (input_is_action_pressed("player_jump"))
        scn->cam.pos.y += speed;

    if (input_is_action_pressed("player_run"))
        scn->cam.pos.y -= speed;
}


static void ingame_end(State *state) {
    SceneIngame *scn = (SceneIngame *)state->scene;
    player_destroy(scn->player);
    world_destroy(scn->world);
    free(state->scene);
}


Scene *ingame_scene(State *state) {
    (void)state;

    SceneIngame *new_scene = ccalloc(1, sizeof *new_scene);
    new_scene->base.tick = ingame_tick;
    new_scene->base.end = ingame_end;

    new_scene->world = world_create();
    new_scene->player = player_create(new_scene->world);

    new_scene->cam = (Camera){ .pos = { 32, 0, 1 }, .up = { 0, 1, 0 }, .fov = (float)M_PI_2 };

    return (Scene *)new_scene;
}
