local love = love
local gpu = require( "gpu" )
local t = {}

local canvas
local shaders = {
  matte = require( "shaders.matte" ),  
}

local meshes = {}
local drawLists = {}
local isDebugging = false
local tf = love.math.newTransform()
local debugTF = love.math.newTransform()

for k in pairs( shaders ) do drawLists[k] = {} end

function t.start()
  canvas = {
    love.graphics.newCanvas(),
    stencil = false,
    depth = true,
  }
end

function t.debug()
  isDebugging = true
end

function t.draw( view, proj )
  
  if isDebugging then
  end
  
  love.graphics.setScissor( 0, 0, love.graphics.getDimensions() )
  love.graphics.setColor( 1, 1, 1, 1 )
  love.graphics.push( "all" )
  love.graphics.setCanvas( canvas )
  love.graphics.clear()
  love.graphics.setDepthMode( "less", true )
  love.graphics.replaceTransform( tf )

  for name, shader in pairs( shaders ) do
    love.graphics.setShader( shader )
    shader:send( "view", "column", view )
    shader:send( "proj", "column", proj )

    for mesh in pairs( drawLists[ name ] ) do
      local modelMatrix = meshes[ mesh ]
      shader:send( "mdl", "column", modelMatrix )
      love.graphics.draw( mesh )
    end
  end

  love.graphics.pop()
  love.graphics.setCanvas()
  love.graphics.setDepthMode( "always", false )
  love.graphics.setShader()
  love.graphics.origin()
  love.graphics.draw( canvas[1] )

  if isDebugging then
    isDebugging = false
    io.flush()
  end
end

function t.update( mesh, modelMatrix )
  meshes[mesh] = modelMatrix
end

function t.add( mesh, shaderName )
  shaderName = shaderName or "matte"
  meshes[mesh] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, {0, 0, 1, 0}, {0, 0, 0, 1} }
  drawLists[shaderName][mesh] = true
end

return t