import Foundation
import simd
import JolkEngine


struct CaveScene: Scene
{
	private var colin = Colin()
	private var world = Collision()
	private var worldModel = RenderMesh<VertexPositionNormalColourTexcoord>.empty
	private var drawEdges = false

	mutating func setup(render: inout any JolkEngine.Renderer)
	{
		colin.setPosition(Vec3f(3.55475903, 0.0667395443, 0.221960306))
		colin.setAngle(Vec2f(-1.47447872, 0.0))
	}
	
	mutating func loadContent(content: inout JolkEngine.ContentManager) throws
	{
		let obj = try ObjReader.read(url: try content.getResource("CaveScene.obj"))
		let mesh: Mesh = try ObjLoader.read(model: obj, content: &content)
		worldModel = try content.create(mesh: mesh)

		if let collision = obj.objects["Collision3D"]
		{
			world.build(obj: obj, collision: collision)
		}
	}
	
	mutating func update(deltaTime: Float)
	{
		colin.update(deltaTime: deltaTime, world: world)
		if Input.instance.keyboard.keyPressed(.c) { drawEdges = !drawEdges }
	}
	
	func draw(render: inout Renderer, deltaTime: Float, aspectRatio aspect: Float)
	{
		render.setProjection(matrix: .perspective(
			fovY: Float.rad(fromDeg: colin.fov),
			aspect: aspect, zNear: 0.1, zFar: 4000.0))
		render.setView(matrix: colin.transform)

		let env = Environment()
		let drawRanges =
		{ [render](range: any Sequence<Int>) in
			for i in range
			{
				let subMesh = worldModel.subMeshes[i]
				render.setMaterial(worldModel.materials[subMesh.material])
				render.draw(mesh: worldModel, subMesh: subMesh, environment: env)
			}
		}
		if colin.position.x < 14 { drawRanges([ 0, 1, 2, 6 ]) }
		else { drawRanges(3...5) }
		if drawEdges { world.draw(render, position: colin.position) }
	}
}
