package main

import (
	"fmt"
	"runtime"
	"time"

	"edgaru089.ml/go/gl01/internal/game"
	_ "edgaru089.ml/go/gl01/internal/render/gpu_preference"
	"github.com/go-gl/gl/all-core/gl"
	"github.com/go-gl/glfw/v3.3/glfw"
)

const (
	//windowWidth  = 852
	//windowHeight = 480
	windowWidth  = 1600
	windowHeight = 900
)

func init() {
	runtime.LockOSThread()
}
func main() {

	if err := glfw.Init(); err != nil {
		panic(err)
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, 1)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, 1)
	win, err := glfw.CreateWindow(windowWidth, windowHeight, "Gl01", nil, nil)
	if err != nil {
		panic(err)
	}
	win.MakeContextCurrent()
	glfw.SwapInterval(1)

	err = gl.Init()
	if err != nil {
		panic(err)
	}

	fmt.Println("OpenGL Version: ", gl.GoStr(gl.GetString(gl.VERSION)))

	game := game.NewGame()
	game.Init(win)

	gl.ClearColor(0.6, 0.8, 1.0, 1)
	gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
	win.SwapBuffers()
	winClock := time.Now()

	fpsClock := time.Now()
	fpsCounter := 0

	for !win.ShouldClose() {

		deltaTime := time.Since(winClock)
		winClock = time.Now()
		game.Update(win, deltaTime)

		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		game.Render(win)

		win.SwapBuffers()
		glfw.PollEvents()

		if time.Since(fpsClock) >= time.Second {
			win.SetTitle(fmt.Sprintf("Gl01 %dFPS", fpsCounter))
			fpsCounter = 0
			fpsClock = time.Now()
		} else {
			fpsCounter++
		}
	}
}
