package main

import (
	"git.solsynth.dev/highland/codingland/pkg/internal/entities"
	"git.solsynth.dev/highland/codingland/pkg/internal/land"
	"git.solsynth.dev/highland/codingland/pkg/internal/land/ui"
	"git.solsynth.dev/highland/codingland/pkg/internal/tiles"
	"github.com/veandco/go-sdl2/ttf"
	"log"
	"runtime"
	"time"

	"github.com/veandco/go-sdl2/sdl"
)

const (
	windowWidth  = 720
	windowHeight = 480
)

func init() {
	runtime.LockOSThread()
}

func main() {
	if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {
		log.Fatalf("Failed to initialize SDL: %s", err)
	}
	defer sdl.Quit()

	if err := ttf.Init(); err != nil {
		log.Fatalf("Failed to initialize SDL ttf: %s", err)
	}
	defer ttf.Quit()

	window, err := sdl.CreateWindow("CodingLand", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, windowWidth, windowHeight, sdl.WINDOW_SHOWN)
	if err != nil {
		log.Fatalf("Failed to create window: %s", err)
	}
	defer window.Destroy()

	renderer, err := sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED|sdl.RENDERER_PRESENTVSYNC)
	if err != nil {
		log.Fatalf("Failed to create renderer: %s", err)
	}
	defer renderer.Destroy()

	font, err := ttf.OpenFont("assets/fonts/NotoSans.ttf", 14)
	if err != nil {
		log.Fatalf("Failed to open font: %s", err)
	} else {
		font.SetStyle(ttf.STYLE_BOLD)
	}
	defer font.Close()

	root := land.NewRootObject()
	root.AddChild(&entities.Player{
		Position: land.Vector2D{X: windowWidth/2 - 25, Y: windowHeight/2 - 25},
		Size:     land.Vector2D{X: 50, Y: 50},
	})
	root.AddChild(&tiles.Tile{
		Position: land.Vector2D{X: 50, Y: 50},
		Size:     land.Vector2D{X: 50, Y: 50},
	})
	root.AddOverlay(&ui.ButtonWidget{
		BaseWidget: land.BaseWidget{
			IsVisible: true,
			Position:  land.Vector2D{X: windowWidth/2 - 60, Y: windowHeight/2 - 25},
			Size:      land.Vector2D{X: 120, Y: 50},
		},
		Label: "Hello, World!",
		Font:  font,
		OnClick: func(_ land.Vector2D) {
			log.Println("你惊扰了古希腊掌控按钮的神")
		},
	})

	// 10ms delay use be 100tps average
	go root.RunEventLoop(10 * time.Millisecond)

	running := true
	for running {
		for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
			switch event.(type) {
			case *sdl.QuitEvent:
				running = false
			default:
				root.HandleUserEvent(event)
			}
		}

		// Draw the entire object tree
		root.Draw(renderer)

		// Show on the screen
		renderer.Present()
	}
}
