-- CameraLoader = require 'lib/camera'

local character = require "lib/character/character"
local testLayout
local TestRunner = require "test.runner"
TestRunner:register(require "test.task")

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

function love.load()
    love.window.setMode(1280, 720, { resizable = true, msaa = 4, vsync = true })
    require "lib/tree" -- важно это сделать после настройки окна
    testLayout = require "lib.simple_ui.level.layout"

    local chars = {
        -- character.spawn("Foodor")
        --     :addBehavior {
        --         Tree.behaviors.residentsleeper.new(),
        --         Tree.behaviors.stats.new(nil, nil, 1),
        --         Tree.behaviors.positioned.new(Vec3 { 3, 3 }),
        --         Tree.behaviors.tiled.new(),
        --         Tree.behaviors.sprite.new(Tree.assets.files.sprites.character),
        --         Tree.behaviors.shadowcaster.new(),
        --         Tree.behaviors.spellcaster.new(),
        --         Tree.behaviors.effects.new()
        --     },
        character.spawn("Foodor")
            :addBehavior {
                Tree.behaviors.residentsleeper.new(),
                Tree.behaviors.stats.new(nil, nil, 1),
                Tree.behaviors.positioned.new(Vec3 { 3, 1 }),
                Tree.behaviors.tiled.new(),
                Tree.behaviors.sprite.new(Tree.assets.files.sprites.character),
                Tree.behaviors.shadowcaster.new(),
                Tree.behaviors.spellcaster.new(),
                Tree.behaviors.effects.new()
            },
        character.spawn("Foodor")
            :addBehavior {
                Tree.behaviors.residentsleeper.new(),
                Tree.behaviors.stats.new(nil, nil, 3),
                Tree.behaviors.positioned.new(Vec3 { 7, 2 }),
                Tree.behaviors.tiled.new(),
                Tree.behaviors.sprite.new(Tree.assets.files.sprites.character),
                Tree.behaviors.shadowcaster.new(),
                Tree.behaviors.spellcaster.new(),
                Tree.behaviors.effects.new()
            },
        -- character.spawn("Baris")
        --     :addBehavior {
        --         Tree.behaviors.residentsleeper.new(),
        --         Tree.behaviors.stats.new(nil, nil, 2),
        --         Tree.behaviors.positioned.new(Vec3 { 5, 5 }),
        --         Tree.behaviors.tiled.new(),
        --         Tree.behaviors.sprite.new(Tree.assets.files.sprites.character),
        --         Tree.behaviors.shadowcaster.new(),
        --         Tree.behaviors.spellcaster.new(),
        --         Tree.behaviors.ai.new(),
        --         Tree.behaviors.effects.new()
        --     },
        -- character.spawn("BOAR")
        --     :addBehavior {
        --         Tree.behaviors.residentsleeper.new(),
        --         Tree.behaviors.stats.new(nil, nil, 2),
        --         Tree.behaviors.positioned.new(Vec3 { 7, 7 }),
        --         Tree.behaviors.tiled.new(),
        --         Tree.behaviors.sprite.new(Tree.assets.files.sprites.boar),
        --         Tree.behaviors.shadowcaster.new(),
        --         Tree.behaviors.spellcaster.new(),
        --         Tree.behaviors.ai.new(),
        --         Tree.behaviors.effects.new()
        --     },
    }

    for id, _ in pairs(chars) do
        Tree.level.turnOrder:add(id)
    end


    Tree.level.turnOrder:endRound()
    print("Now playing:", Tree.level.turnOrder.current)
end

local lt = "0"
function love.update(dt)
    TestRunner:update(dt) -- закомментировать для отключения тестов

    local t1 = love.timer.getTime()
    require('lib.utils.task').update(dt)
    Tree.controls:poll()
    Tree.level.camera:update(dt) -- сначала логика камеры, потому что на нее завязан UI
    testLayout:update(dt)        -- потом UI, потому что нужно перехватить жесты и не пустить их дальше
    Tree.panning:update(dt)
    Tree.level:update(dt)
    Tree.audio:update(dt)

    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:draw()

    testLayout:draw()
    love.graphics.setColor(1, 1, 1)

    love.graphics.setFont(Tree.fonts:getTheme("Roboto_Mono"):getVariant("small"))
    local mousePosX, mousePosY = love.mouse.getPosition()
    local mousePos = Tree.level.camera:toWorldPosition(Vec3 { mousePosX, mousePosY }):floor()
    local stats = "fps: " ..
        love.timer.getFPS() ..
        " lt: " .. lt ..
        " dt: " .. dt ..
        " mem: " .. string.format("%.2f MB", collectgarbage("count") / 1000) ..
        " mouse pos: " .. tostring(mousePos)
    love.graphics.print(stats, 10, 10)

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

function love.resize(w, h)
    local render = Tree.level.render
    if not render then return end
    render:free()
    Tree.level.render = (require "lib.level.render").new { w = w, h = h }
end
