class = require '30log'

local HC = require 'hardoncollider'
-- has to come before the sti initialization so I can add the collision tiles
collider = HC(100)

local sti = require "sti"

local character = require "character"
local ui = require "ui"

local characters = {}

function love.load()
  windowWidth = love.graphics.getWidth()
  windowHeight = love.graphics.getHeight()

  map = sti.new("assets/map")
  collision = map:getCollisionMap("collision")

  initCharacters()
end

function love.update(dt)
  for _, char in ipairs(characters) do
    if char.relevantKeys then
      for _, relevantKey in ipairs(char.relevantKeys) do
        if love.keyboard.isDown(relevantKey) then
          char.controller:sendKey(relevantKey)
        end
      end
    end
  end

  collider:update(dt)
  map:update(dt)
end

function love.draw()
  -- Translation would normally be based on a player's x/y
  local translateX = 0
  local translateY = 0

  -- Draw Range culls unnecessary tiles
  map:setDrawRange(translateX, translateY, windowWidth, windowHeight)

  map:draw()

  --debugDrawing()
end

function debugDrawing()
  -- draw collision shapes for debugging
  for shape in pairs(collider:shapesInRange(0, 0, windowWidth, windowHeight)) do
   shape:draw()
  end

  -- Draw Collision Map (useful for debugging)
  map:drawCollisionMap(collision)
end

function initCharacters()
  local collisionBoxOffset = 5

  map:addCustomLayer("character layer", 4)

  local characterLayer = map.layers["character layer"]
  characterLayer.sprites = {}

  for _, char in pairs(map.layers["characters"].objects) do
    local filename = "characters/" .. char.name .. ".lua"
    local charinfo = love.filesystem.load(filename)()
    charinfo.x = char.x - character.width / 4
    charinfo.y = char.y

    charinfo.controller.charinfo = charinfo

    charinfo.image = love.graphics.newImage(charinfo.spritesheet)
    charinfo.controller:init()

    table.insert(characterLayer.sprites, {info = charinfo})
    table.insert(characters, charinfo)
  end

  -- Draw callback for Custom Layer
  function characterLayer:draw()
    table.sort(self.sprites, character.sortNorthSouth)

    for _, sprite in pairs(self.sprites) do
      local x = math.floor(sprite.info.x)
      local y = math.floor(sprite.info.y)

      local offsetX = sprite.info.pose.offsetX * character.width
      local offsetY = sprite.info.pose.offsetY * character.height

      local quad = love.graphics.newQuad(offsetX, offsetY, character.width, character.height, sprite.info.image:getWidth(), sprite.info.image:getHeight())
      love.graphics.draw(sprite.info.image, quad, x, y)
    end
  end

  map.layers["characters"].visible = false
end


