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 scene = require( "scene" )
  return scene.load( t )
end

function t.draw()
  
  world.draw( player.view, player.proj, player.x, player.z )
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( world.circles )
    world.update( player )
  end
  io.flush()
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
    if world.bell.near then return world.bell.ringAll( world.bell.near ) end
    if world.phone.canPickup then return world.phone.pickup() end
  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