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

local canvas

local meshes = {}
local isDebugging = false
local tf = love.math.newTransform()
local debugTF = love.math.newTransform()
local sky
local bell
local contempra
local terrain
local spike
local water
local light = require( "level.light" )

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

--  water = require( "models.water" )
  sky = require( "models.sky" )
  bell = require( "models.bell" )
  t.bell = bell
  contempra = require( "models.contempra" )
  t.phone = contempra
  t.phone.ring()
  terrain = require( "models.terrain" )
  spike = require( "models.spike" )

  local n = 1
  t.circles = {}
  local function addCircles( obj )
    for i, circle in ipairs( obj.circles ) do
      t.circles[n] = circle
      n=n+1
    end
  end


  addCircles( contempra )
  addCircles( bell )
  addCircles( spike )

end

function t.debug()
  isDebugging = true
end

local text = love.graphics.newText( love.graphics.getFont() )
function t.draw( view, proj, x, z )

  if isDebugging then
  end


  love.graphics.push( "all" )

  love.graphics.setColor( 1,1,1,1 )
  love.graphics.setScissor( 0, 0, love.graphics.getDimensions() )
  love.graphics.setCanvas( canvas )
  love.graphics.clear()
  love.graphics.setDepthMode( "less", true )
  love.graphics.replaceTransform( tf )
  love.graphics.setMeshCullMode( "back" )

  sky.draw( view, proj, light )
  terrain.draw( view, proj, light )
  bell.draw( view, proj, light )
  spike.draw( view, proj, light )
  contempra.draw( view, proj, light, x, z )


  love.graphics.pop()
  love.graphics.setColor( 1, 1, 1, 1 )
  love.graphics.draw( canvas[1] )


  if t.msg then
    text:set( t.msg )
    text:setf( t.msg, text:getWidth(), "center" )
  end
  local textx = 0.5 * (love.graphics.getWidth() - text:getWidth())
  local w = text:getWidth()
  if w > 0 then
    love.graphics.setColor( 0,0,0,0.9 )
    love.graphics.rectangle( "fill", textx - 10, 0, w + 20, text:getHeight() + 20 )
    love.graphics.setColor( 1,0,0,1 )
    love.graphics.draw( text, textx, 10 )
  end
end


function t.update( player )

  local msg
  light.update( player.enteringCircle )

  msg = bell.update( player.enteringCircle, player.leavingCircle, player.x, player.z )
  local phoneMsg = contempra.update( player )
  msg = msg or phoneMsg
  t.msg = msg or ""
end

function t.transposeBells( i, j )
  return bell.transpose( i, j )
end

function t.pickupPhone()
  return contempra.pickup()
end

function t.ring( idx )
  return bell.ring( idx )
end

function t.ringAll( i )
  return bell.ringAll( i )
end

return t