package uk.co.rossbinden.transferencevoid.system

import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.EntitySystem
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.utils.Disposable
import com.badlogic.gdx.utils.Scaling
import com.badlogic.gdx.utils.viewport.ScalingViewport
import uk.co.rossbinden.transferencevoid.component.RENDERABLE
import uk.co.rossbinden.transferencevoid.component.RENDERABLE_FAMILY

class RenderSystem(
    viewportWidth: Float = Gdx.graphics.width.toFloat(),
    viewportHeight: Float = Gdx.graphics.height.toFloat()
): EntitySystem(1000), Disposable {

    val camera = OrthographicCamera()
    val viewport = ScalingViewport(Scaling.none, viewportWidth, viewportHeight, camera)
    val stage = Stage(viewport)

    init {
        camera.setToOrtho(false, viewportWidth, viewportHeight)
        stage.addActor(object: Actor() {
            override fun draw(batch: Batch, parentAlpha: Float) {
                val entities = engine.getEntitiesFor(RENDERABLE_FAMILY)
                entities.forEach { entity -> processEntity(entity, Gdx.graphics.deltaTime) }
            }
        })
    }

    override fun update(deltaTime: Float) {
        Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
        stage.act(deltaTime)
        stage.draw()
    }

    fun processEntity(entity: Entity, deltaTime: Float) {
        RENDERABLE.get(entity).renderFunction.invoke(deltaTime, stage.batch)
    }

    override fun dispose() {
        stage.dispose()
    }

}