package main

import rl "vendor:raylib"

import "core:fmt"

GameState :: struct {
	camera:     rl.Camera3D,
	cam_offset: rl.Vector3,
	gfx_state:  GfxState,
	car:        Car,
	sound:      EngineSound,
}


init_game_state :: proc() -> GameState {

	state: GameState
	state.gfx_state = gfx_init()

	state.cam_offset = rl.Vector3{0, 2, -6}

	state.car = init_car()

	state.sound = engine_sound_init()

	state.camera = rl.Camera3D {
		position   = state.car.pos + state.cam_offset,
		target     = state.car.pos,
		up         = {0, 1, 0},
		fovy       = 45.0,
		projection = .PERSPECTIVE,
	}
	return state
}

cleanup_game_state :: proc(state: ^GameState) {
	gfx_unload(&state.gfx_state)
	engine_sound_unload(&state.sound)
}

update_game_state :: proc(state: ^GameState) {
	if rl.Vector3Length(state.car.vel) != 0 {
		state.camera.position =
			state.car.pos +
			rl.Vector3Normalize(state.car.vel) * -7 +
			rl.Vector3{0, 2, 0}
		// } else {
		// 	state.camera.position = state.car.pos + state.cam_offset
	}
	// state.camera.position = state.car.pos + state.cam_offset
	state.camera.target = state.car.pos + rl.Vector3{0, 1, 0}

	update_car(&state.car)

	engine_sound_update(&state.sound, state.car.engine_state.rpm)

	cam_pos := state.camera.position
	gfx_update(&state.gfx_state, &cam_pos)
}

draw_game_state :: proc(state: ^GameState) {
	rl.ClearBackground(rl.GetColor(0x181825FF)) // Dark background
	rl.BeginMode3D(state.camera)
	{
		draw_3d(state)
	}
	rl.EndMode3D()

	draw_ui(state)


}

draw_3d :: proc(state: ^GameState) {
	rl.DrawGrid(200, 2.0)
	gfx_draw_car(&state.gfx_state, state.car.pos, state.car.wheel_yaw)
}

draw_ui :: proc(state: ^GameState) {
	draw_gauges(&state.car)
	draw_stats(&state.car)
}
