package ru.dbotthepony.kstarbound.client.gl.properties

import org.lwjgl.opengl.GL45
import ru.dbotthepony.kstarbound.client.StarboundClient
import ru.dbotthepony.kstarbound.client.gl.GLObject
import ru.dbotthepony.kstarbound.client.gl.checkForGLError

class GLTexturesTracker<T : GLObject>(maxValue: Int) {
	private val client = StarboundClient.current()
	private val values = arrayOfNulls<GLObject>(maxValue)

	operator fun get(index: Int): T? {
		return values[index] as T?
	}

	operator fun set(index: Int, value: T?) {
		client.ensureSameThread()
		require(value == null || client === value.client) { "$value does not belong to $client" }

		if (values[index] === value)
			return

		if (value == null) {
			GL45.glBindTextureUnit(index, 0)
			checkForGLError()
		} else {
			GL45.glBindTextureUnit(index, value.pointer)
			checkForGLError()
		}

		values[index] = value
	}
}
