package main

import (
	"fmt"
	"runtime"
	"time"

	"github.com/Edgaru089/gl01/internal/render"
	"github.com/Edgaru089/gl01/internal/util/itype"
	"github.com/Edgaru089/gl01/internal/world"
	"github.com/go-gl/gl/all-core/gl"
	"github.com/go-gl/glfw/v3.3/glfw"
)

const (
	windowWidth  = 852
	windowHeight = 480
)

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

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

	glfw.WindowHint(glfw.Resizable, 0)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, 1)
	win, err := glfw.CreateWindow(windowWidth, windowHeight, "Cube", 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)))

	var c, cm world.Chunk
	c.SetBlock(0, 0, 0, 2)
	c.SetBlock(1, 0, 2, 1)
	c.SetBlock(2, 0, 2, 3)
	cm.SetChunkID(-1, -1)
	cm.SetBlock(15, 0, 15, 5)
	cm.SetBlock(15, 1, 15, 6)

	world.DefaultWorld.SetChunk(0, 0, &c)
	world.DefaultWorld.SetChunk(-1, -1, &cm)

	var rotY, rotZ float32 = 135, -45
	render.DefaultWorldRenderer.LookAt(itype.Vec3f{3, 3, 3}, rotY, rotZ)
	render.DefaultWorldRenderer.SetAspect(float32(windowWidth) / float32(windowHeight))
	render.DefaultWorldRenderer.SetFovY(45)
	render.DefaultWorldRenderer.Init(&world.DefaultWorld)

	gl.ClearColor(1, 1, 1, 1)
	winClock := time.Now()
	for !win.ShouldClose() {

		deltaTime := time.Since(winClock)
		winClock = time.Now()

		if win.GetKey(glfw.KeyLeft) == glfw.Press {
			rotY += float32(deltaTime.Seconds()) * 100
		}
		if win.GetKey(glfw.KeyRight) == glfw.Press {
			rotY -= float32(deltaTime.Seconds()) * 100
		}
		if win.GetKey(glfw.KeyUp) == glfw.Press {
			rotZ += float32(deltaTime.Seconds()) * 100
		}
		if win.GetKey(glfw.KeyDown) == glfw.Press {
			rotZ -= float32(deltaTime.Seconds()) * 100
		}
		render.DefaultWorldRenderer.LookAt(itype.Vec3f{3, 3, 3}, rotY, rotZ)

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

		render.DefaultWorldRenderer.Render(&world.DefaultWorld)

		win.SwapBuffers()
		glfw.PollEvents()
	}
}
