local ease = require("love_src.src.world.2_town_square.pseudo3d.ease")

local utils = {}

local function drawQuad(slice, image, quads, x1, y1, x2, y2, w1, w2, h1, h2, sw, sh)
  for i = 1, #quads do
    local percent = ease.percentRemaining(i, #quads)
    local destY = ease.interpolate(y1, y2, percent)
    local destX = ease.interpolate(x1, x2, percent)
    local destW = ease.interpolate(w1, w2, percent)
    local destH = ease.interpolate(h1, h2, percent)

    if (slice == "vertical") then
      love.graphics.draw(image,quads[i],
        destX, destY, 0, destW / sw, 1
      )
    elseif (slice == "horizontal") then
      love.graphics.draw(image,quads[i],
        destX, destY, 0, 1, destH / sh
      )
    end
  end
end

local function drawSection(texture, key, x1, y1, x2, y2, w1, w2, h1, h2, resolution)
  local image = texture[key].image
  local quads = texture[key].quads

  local sw, sh = image:getDimensions()

  if (key == "floor") then
    drawQuad("vertical", image, quads,
      x1, y1,
      x2, y2,
      w1, w2,
      h1, h2,
      sw, sh
    )
  elseif (key == "ceil") then
    drawQuad("vertical", image, quads,
      x1, -y1 + resolution[2]/2,
      x2, -y2 + resolution[2]/2,
      w1, w2,
      h1, h2,
      sw, sh
    )
  elseif (key == "wallL") then
    drawQuad("horizontal", image, quads,
      x1, -y1 + h1,
      x2, -y2 + h2,
      w1, w2,
      h1, h2,
      sw, sh
    )
  elseif (key == "wallR") then
    drawQuad("horizontal", image, quads,
      x1 + w1, -y1,
      x2 + w2, -y2,
      w1, w2,
      h1 + y1,
      h2 + y2,
      sw, sh
    )
  end
end

function utils.draw(p1screenpos, p2screenpos, p1screensize, p2screensize, texture, resolution, maxy)
  local x1 = p1screenpos[1]
  local y1 = p1screenpos[2]
  local x2 = p2screenpos[1]
  local y2 = p2screenpos[2]

  local w1 = p1screensize[1]
  local w2 = p2screensize[1]

  local h1 = (y1)
  local h2 = (y2)

  local x1e = x1 + w1
  local x2e = x2 + w2

  drawSection(texture, "wallL", x1 , y1, x2, y2, w1, w2, h1, h2, resolution)
  drawSection(texture, "wallR", x1 , y1, x2, y2, w1, w2, h1, h2, resolution)
  drawSection(texture, "floor", x1 , y1, x2, y2, w1, w2, h1, h2, resolution)
  drawSection(texture, "ceil", x1 , y1, x2, y2, w1, w2, h1, h2, resolution)

end

return utils
