package me.eater.threedom.gl

import me.eater.threedom.gl.GL.stack
import me.eater.threedom.gl.exception.ShaderCompilationException
import org.lwjgl.opengl.GL20.*
import org.lwjgl.system.MemoryUtil

data class Shader(val shaderId: Int, val shaderType: ShaderType) {
    enum class ShaderType(val glId: Int) {
        Fragment(GL_FRAGMENT_SHADER),
        Vertex(GL_VERTEX_SHADER);
    }

    fun delete() {
        glDeleteShader(shaderId)
    }

    companion object {
        fun create(source: String, shaderType: ShaderType): Shader {
            val shaderId = glCreateShader(shaderType.glId)
            glShaderSource(shaderId, source)
            glCompileShader(shaderId)
            val success = stack.mallocInt(1)
            glGetShaderiv(shaderId, GL_COMPILE_STATUS, success)
            if (success.get(0) == 0) {
                throw ShaderCompilationException(glGetShaderInfoLog(shaderId))
            }

            return Shader(shaderId, shaderType)
        }
    }
}
