local BaseMap = require "core.modules.world.maps.parent"
local BattleMap = BaseMap:extend()

function BattleMap:new(world, maptype, mapname)
  BattleMap.super.new(self, world)
  self:setPadding(0, 128, 0, 0)
  self.directory  = game.utils.getMapDirectory(maptype, mapname)
  self.mappath    = game.utils.getMapPath(maptype, mapname)

  self.background = love.graphics.newImage(self.directory .. "background.png")
  self.data       = require(self.mappath)
  self.assets     = world.scene.assets

  self:addParallax()
end

function BattleMap:loadCollisions()
  local w, h = self:getDimensions()
  self.world:newCollision("floor", 0, 0, -16, w, h, 16)
  for i, block in ipairs(self.data.blocks) do
    self:addBlock(block[1], block[2], block[3], block[4], block[5], block[6])
  end
end

function BattleMap:addBlock(x, y, w, h, top, bottom)
  if (self.assets.images[top] == nil) then
    self.assets:addImage(top, self.directory .. top .. ".png")
  end
  if (self.assets.images[bottom] == nil) then
    self.assets:addImage(bottom, self.directory .. bottom .. ".png")
  end
  self.world.obj.collisions["textured"](self.world, x*2, y, 0, w*2, h, 48, top, bottom)
end

function BattleMap:getDimensions()
  local w, h = self.background:getDimensions()
  return w, (h/2)
end

function BattleMap:loadPlayers()
  self.world:addPlayer(16, 16, 0, 1)
end

function BattleMap:loadActors()
  -- Empty Placeholder function
end

function BattleMap:draw()
  love.graphics.draw(self.background, 0, 0, 0, 1, 0.5)
end

function BattleMap:addParallax()
  self.parallax = {}

  for i,layerdata in ipairs(self.data.parallax) do
    local layer = {}
    layer.basex      = layerdata[1]
    layer.basey      = layerdata[2]
    layer.background = love.graphics.newImage(self.directory .. layerdata[7] .. ".png")
    local w, h = layer.background:getDimensions()
    layer.w = w
    layer.h = h

    if (layerdata[5]) then
      layer.repeatx = math.ceil(424/w + 1)
    else
      layer.repeatx = 1
    end

    if (layerdata[6]) then
      layer.repeaty = math.ceil(240/h + 1)
    else
      layer.repeaty = 1
    end

    layer.decalx = layerdata[3]
    layer.decaly = layerdata[4]

    table.insert(self.parallax, layer)
  end
end

function BattleMap:drawParallax(x, y, w, h)
  for i1, layer in ipairs(self.parallax) do
    local x = math.floor((x)*layer.decalx) % layer.w

    for i=1, layer.repeatx do
      for j=1, layer.repeaty do
        local xx = math.floor(layer.basex + (layer.w * (i-1)) - x)
        local yy = math.floor(layer.basey + (layer.h * (j-1)) - (y+96)*layer.decaly)
        love.graphics.draw(layer.background, xx, yy)
      end
    end
  end
end

return BattleMap
