local board = require 'board'
local consts = require 'constants'
local entity = require 'entity'
local tile = require 'tile'
local event = require 'event'
local menu = require 'menu'
local draw = require 'draw'

state = {
   loadMap = function(self, name)
      self.board = board.loadBoardFromTiled('areas/' .. name .. '.lua')
   end,
   keys = {},
}

local sprites = {}

function fromScreen(x, y)
   return math.floor(x / consts.tileSize), math.floor(y / consts.tileSize)
end

function love.load()
   state.t = 0
   state.message = nil
   debug = ''

   state.board = board.loadBoardFromTiled('areas/main.lua')
   state.char = entity.Entity:new(
      state, 3 * 24, 3 * 24, 'character')

   state.canvas = love.graphics.newCanvas(
      consts.boardWidth * consts.tileSize,
      consts.boardHeight * consts.tileSize)
   state.normals = love.graphics.newCanvas(
      consts.boardWidth * consts.tileSize,
      consts.boardHeight * consts.tileSize)
   state.canvas:setFilter('nearest', 'nearest')
   state.normals:setFilter('nearest', 'nearest')
   state.spritesheet = love.graphics.newImage('tiles/spritesheet.png')
   state.spriteNormals = love.graphics.newImage('tiles/spritesheet-normal.png')

   love.window.setMode(consts.tileSize * consts.boardWidth * consts.scale,
                       consts.tileSize * consts.boardHeight * consts.scale)

   love.graphics.setNewFont('font.ttf', 16)
end

function love.update()
   state.t = state.t + 1
   state.char.dx = 0
   state.char.dy = 0
   for key, enabled in pairs(state.keys) do
      if enabled and event.keys.pressed[key] then
         event.keys.pressed[key](state)
      end
   end
   state.char:move()
end

function love.keypressed(key)
   if state.message then
      state.message = nil
   else
      state.keys[key] = true
   end
end

function love.keyreleased(key)
      state.keys[key] = nil
end

function love.draw()
   draw.drawAll(state)
end
