-- CameraLoader = require 'lib/camera'

local character = require "lib/character/character"
require "lib/tree"
local testLayout = require "lib.simple_ui.level.layout"

function love.conf(t)
    t.console = true
end

function love.load()
    character.spawn("Foodor", Tree.assets.files.sprites.character, nil, nil, 1)
    character.spawn("Baris", Tree.assets.files.sprites.character, Vec3 { 3, 3 }, nil, 2)
    character.spawn("Foodor Jr", Tree.assets.files.sprites.character, Vec3 { 0, 3 }, nil, 3)
    character.spawn("Baris Jr", Tree.assets.files.sprites.character, Vec3 { 0, 6 }, nil, 4)
    for id, _ in pairs(Tree.level.characters) do
        Tree.level.turnOrder:add(id)
    end
    Tree.level.turnOrder:endRound()
    print("Now playing:", Tree.level.turnOrder.current)
    love.window.setMode(1280, 720, { resizable = true, msaa = 4, vsync = true })
end

local lt = "0"
function love.update(dt)
    local t1 = love.timer.getTime()
    Tree.controls:poll()
    testLayout:update(dt) -- логика UI-слоя должна отработать раньше всех, потому что нужно перехватить жесты и не пустить их дальше
    Tree.panning:update(dt)
    Tree.level:update(dt)

    -- для тестов очереди ходов
    -- удалить как только появится ui для людей
    if Tree.controls:isJustPressed("endTurnTest") then
        Tree.level.turnOrder:next()
        print("Now playing:", Tree.level.turnOrder.current)
    end
    if Tree.controls:isJustPressed("toggleTurns") then
        print('toggle turns')
        Tree.level.turnOrder:toggleTurns()
    end

    Tree.controls:cache()

    local t2 = love.timer.getTime()
    lt = string.format("%.3f", (t2 - t1) * 1000)
end

local function coverTransform(img, containerW, containerH)
    local iw, ih = img:getWidth(), img:getHeight()
    local scale = math.max(containerW / iw, containerH / ih)
    local sw, sh = iw * scale, ih * scale
    local offsetX = (containerW - sw) * 0.5
    local offsetY = (containerH - sh) * 0.5
    return scale, offsetX, offsetY, sw, sh
end

local dt = "0"
function love.draw()
    local t1 = love.timer.getTime()
    local scale, ox, oy = coverTransform(Tree.assets.files.cats, love.graphics.getWidth(), love.graphics.getHeight())

    love.graphics.push()
    love.graphics.translate(ox, oy)
    love.graphics.scale(scale, scale)
    love.graphics.draw(Tree.assets.files.cats, 0, 0)
    love.graphics.pop()

    Tree.level.camera:attach()

    Tree.level:draw()

    Tree.level.camera:detach()
    testLayout:draw()
    love.graphics.setColor(1, 1, 1)

    local stats = "fps: " ..
        love.timer.getFPS() ..
        " lt: " .. lt .. " dt: " .. dt .. " mem: " .. string.format("%.2f MB", collectgarbage("count") / 1000)
    love.graphics.print(stats, 10, 10)

    local t2 = love.timer.getTime()
    dt = string.format("%.3f", (t2 - t1) * 1000)
end
