local utils = require "lib.utils.utils"

--- @class Level
--- @field size Vec3
--- @field characters Character[]
--- @field deadIds Id[]
--- @field characterGrid CharacterGrid
--- @field lightGrid LightGrid
--- @field selector Selector
--- @field camera Camera
--- @field tileGrid TileGrid
--- @field turnOrder TurnOrder
--- @field render Render
local level = {}
level.__index = level

--- @param type "procedural"|"handmaded"
--- @param template Procedural|Handmaded
local function new(type, template)
    local size = Vec3 { 30, 30 } -- magic numbers for testing purposes only
    print(type, template, size)

    Tree.audio:play(Tree.assets.files.audio.music.level1.battle)

    return setmetatable({
        size = size,
        characters = {},
        deadIds = {},
        characterGrid = (require "lib.level.grid.character_grid").new(),
        lightGrid = (require "lib.level.grid.light_grid").new(),
        tileGrid = (require "lib.level.grid.tile_grid").new(type, template, size),
        selector = (require "lib.level.selector").new(),
        camera = (require "lib.level.camera").new(),
        turnOrder = (require "lib.level.turn_order").new(),
        render = (require "lib.level.render").new {},
        weather = (require "lib.level.weather").new { ambientLight = Vec3 { 0.5, 0.5, 0.5 }, skyLight = Vec3 { 0.85, 0.55, 0.40 } }
    }, level)
end

function level:update(dt)
    utils.each(self.deadIds, function(id)
        self.characters[id] = nil
        self.turnOrder:remove(id)
    end)
    self.deadIds = {}

    self.characterGrid:reload()
    self.lightGrid:reload()
    utils.each(self.characters, function(el)
        el:update(dt)
    end)

    self.selector:update(dt)
end

function level:draw()
    self.render:clear()
    self.tileGrid:draw()
    utils.each(self.characters, function(char)
        char:draw()
    end)

    self.render:draw()
end

return {
    new = new
}
