package game

import (
	"log"
	"mvvasilev/last_light/render"
	"os"
	"time"
)

const TICK_RATE int64 = 50 // tick every 50ms ( 20 ticks per second )

type GameContext struct {
	renderContext *render.RenderContext

	game *Game
}

func CreateGameContext() *GameContext {
	gc := new(GameContext)

	rc, err := render.CreateRenderContext()

	if err != nil {
		log.Fatalf("%~v", err)
	}

	gc.renderContext = rc
	gc.game = CreateGame()

	return gc
}

func (gc *GameContext) Run() {
	lastTick := time.Now()

	for {
		deltaTime := 1 + time.Since(lastTick).Microseconds()
		lastTick = time.Now()

		for _, e := range gc.renderContext.CollectInputEvents() {
			gc.game.Input(e)
		}

		stop := !gc.game.Tick(deltaTime)

		if stop {
			gc.renderContext.Stop()
			os.Exit(0)
			break
		}

		drawables := gc.game.CollectDrawables()
		gc.renderContext.Draw(deltaTime, drawables)
	}
}
