local projection = require("lib.choro.projection")

local UV = require("engine.utils.obj3d.texture.uv")
local quadToUV = UV.quadToUV
local imageToUV = UV.imageToUV

local QuadCache = require("engine.cache.loveapi.quadcache").obj

local utils = {}

function utils.drawstatic(segment, roadWidth, resolution)
  -- render roadside sprites
  local w2 = resolution[1]/2
  for i = 1, #segment.sprites do
    local sprite        = segment.sprites[i].source;
    local spriteoffset  = segment.sprites[i].offset;

    local spritePath  = segment.sprites[i].data.path;
    local spriteType  = segment.sprites[i].data.type;
    local spriteState  = segment.sprites[i].data.state;

    local quad
    local img
    if (spriteType == "aseprite") then
      img = sprite.image
      quad = sprite.frame.quad
    else
      img = sprite
      quad = QuadCache:load(spritePath, 0, 0, 1, 1, img:getWidth(), img:getHeight(), spriteType)
    end

    local u, v, nu, nv  = quadToUV(quad)

    local spriteScale = segment.p1.screen.scale;
    local spriteX     = segment.p1.screen.pos.x + (spriteScale * spriteoffset * roadWidth * w2);
    local spriteY     = segment.p1.screen.pos.y;

    local offsetX
    if (spriteoffset < 0) then
      offsetX = -1
    else
      offsetX = 0
    end
    local offsetY = -1

    --  scale for projection AND relative to roadWidth (for tweakUI)
    local destW  = (img:getWidth() * spriteScale * w2) * (projection.getSpriteScale(resolution[1]/3) * roadWidth);
    local destH  = (img:getHeight() * spriteScale * w2) * (projection.getSpriteScale(resolution[1]/3) * roadWidth);

    local destX = spriteX + (destW * (offsetX or 0));
    local destY = spriteY + (destH * (offsetY or 0));

    local clipH = 0;
    if (segment.clip) then
      clipH = math.max(0, destY+destH-segment.clip)
    end

    if (clipH < destH) then
      local _nv = nv - (nv * clipH/destH)

      local _destH = destH - clipH

      local _quad = quad
      if (_nv ~= nv) then
        _quad = QuadCache:load(spritePath, u, v, nu, _nv, img:getWidth(), img:getHeight(), spriteType, spriteState)
      end
      love.graphics.draw(img, _quad, destX, destY, 0, destW, _destH)
    end
  end
end

return utils
