import momentum.rt.MomentumRuntime
import momentum.rt.render.Material
import momentum.rt.render.Material.*
import momentum.rt.render.Pipeline
import momentum.rt.render.ShaderProgram
import momentum.rt.render.Texture2D
import momentum.rt.resource.ClassPathResourceLoader
import momentum.rt.resource.ResourceManager
import org.lwjgl.BufferUtils
import org.lwjgl.opengl.Display
import org.lwjgl.opengl.DisplayMode
import java.io.InputStream

import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL30.*
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.*
import java.nio.FloatBuffer




fun main(args: Array<String>) {
    Display.setDisplayMode(DisplayMode(800, 600))
    Display.create()

    MomentumRuntime.init()

    val manager = ResourceManager()
    manager.registerLoader(ClassPathResourceLoader())

    val texture: Texture2D = manager.load("dlight.tex")
    val program: ShaderProgram = manager.load("dlight.shader")

    glUseProgram(program.programID)
    run {
        val uniformLoc = glGetUniformLocation(program.programID, "tex")
        glUniform1i(uniformLoc, 0)
    }

    class RenderContext() {
        val vao: Int
        val vbo: Int
        val ibo: Int

        init {
            vbo = glGenBuffers()
            ibo = glGenBuffers()

            vao = glGenVertexArrays()

            glBindVertexArray(vao)

            glBindBuffer(GL_ARRAY_BUFFER, vbo)
            run {
                val arr = listOf(
                    0.5f, 0.5f, 0f,
                   -0.5f, 0.5f, 0f,
                   -0.5f, -0.5f, 0f,
                    0.5f, -0.5f, 0f
                ).toFloatArray()
                val buf = BufferUtils.createFloatBuffer(12)
                buf.put(arr).flip()
                glBufferData(GL_ARRAY_BUFFER, buf, GL_STATIC_DRAW)
            }

            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo)
            run {
                val arr = listOf(0, 1, 2, 0, 2, 3).toIntArray()
                val buf = BufferUtils.createIntBuffer(6)
                buf.put(arr).flip()
                glBufferData(GL_ELEMENT_ARRAY_BUFFER, buf, GL_STATIC_DRAW)
            }

            glEnableVertexAttribArray(0)
            glVertexAttribPointer(0, 3, GL_FLOAT, false, 4 * 3, 0)

            glBindVertexArray(0)
        }
    }

    val ctx = RenderContext()

    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glClearColor(0.5f, 0.3f, 0.3f, 1.0f)

    while (!Display.isCloseRequested()) {
        glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)

        glBindTexture(GL_TEXTURE_2D, texture.textureID)

        glBindVertexArray(ctx.vao)
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0)
        glBindVertexArray(0)

        Display.update()
    }

    Display.destroy()
}
