local love = assert( love )
local player = require( "player" )
local settings = require( "settings" )
local world = require( "level.world" )
local mat = require( "mat4" )
local t = {}

local frameStart = love.timer.getTime()

local rockTexture = love.graphics.newImage( "tex/rock.png", { mipmaps = true } )
rockTexture:setWrap( "repeat", "repeat" )
function t.play()
  --love.graphics.setNewFont( 14 )
  t.mousepressed() --grab window
  player:setTurnRate( settings.mouseSensitivity.val )
  player:setFOV( settings.FOV.val )
  world.start()
  
  --[[local spike = require( "models/spike" )
  spike:setTexture( rockTexture )
  renderer.add( spike )
  renderer.update( spike, mat.TRS( 0.3, 12, 0.3, 0, 0, 0, 4, 0, 3) )]]
  
  local scene = require( "scene" )
  return scene.load( t )
end

function t.draw()
  
  world.draw( player.view, player.proj )
  
  local y = 0
  for k, v in pairs(love.graphics.getStats()) do
    love.graphics.print( k, 0, y )
    love.graphics.print( v, 200, y )
    y = y + 16
  end
  
  love.graphics.print( player:tostring(), 0, y )
end


local updateTimeRemaining = 0
function t.update( dt )
  if not love.mouse.getRelativeMode() then return end
  
  player:updateDesiredDirection(
    love.keyboard.isScancodeDown( settings.keyForward.val ),
    love.keyboard.isScancodeDown( settings.keyLeft.val    ),
    love.keyboard.isScancodeDown( settings.keyRight.val    ),
    love.keyboard.isScancodeDown( settings.keyBack.val   )
  )
  
  
  updateTimeRemaining = updateTimeRemaining + dt
  while updateTimeRemaining >= player.rate do
    updateTimeRemaining = updateTimeRemaining - player.rate
    player:update()
  end
  
  world.update( player )
end

function t.mousepressed( x, y, button, isTouch, presses )
  love.mouse.setRelativeMode( true )
  love.mouse.setVisible( false )
end

function t.keypressed( key, code, isrepeat )
  if code == "escape" then
    love.mouse.setRelativeMode( false )
    love.mouse.setVisible( true )
  end
  if code == settings.keyUse.val then
    
  end
  if code == "2" then
    local strings = require( "i18n" )
    local slideshow = require( "scenes.slideshow" )
    return slideshow.play( strings.win, love.event.quit, "tex/win.jpg" )
  end
  if code == "3" then
    return world.targetLight( math.random( 1, 7 ) )
  end
  if code == "4" then
    return world.pickupPhone()
  end
  if code == "1" then
    return world.transposeBells( 2, 7 )
  end
end

function t.keyreleased( key, code )
  
end

function t.mousemoved( x, y, dx, dy, isTouch )
  if not love.mouse.getRelativeMode() then return end
  player:turn( dx, dy )
end

return t