-- core/assets :: a simple assets manager, aim to put every assets in a simple
-- serie of table in order to find them easily.

--[[
  Copyright © 2019 Kazhnuz

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]

local AssetManager = Object:extend()

function AssetManager:new()
    self.locals = {}
    self.globals = {}
    self.updatables = {}

    self.isActive = true
end

function AssetManager:update(dt)
    if (self.isActive) then
        for key, updatable in pairs(self.updatables) do
            updatable:update(dt)
        end
    end
end

function AssetManager:add(name, asset, isGlobal)
    if (isGlobal == true) then
        self:addGlobal(name, asset)
    else
        self:addLocal(name, asset)
    end
end

function AssetManager:addGlobal(name, asset)
    self.globals[name] = asset
end

function AssetManager:addLocal(name, asset)
    self.locals[name] = asset
end

function AssetManager:clear()
    self.locals = {}
    self.globals = {}
    collectgarbage()
end

function AssetManager:clearLocal()
    self.locals = {}
end

function AssetManager:get(name)
    local asset
    if self.locals[name] ~= nil then
        asset = self.locals[name]
    else
        asset = self.globals[name]
    end

    if (asset ~= nil) then
        return asset
    else
        core.debug:fail("core.assets", "L'asset " .. name .. " n'existe pas.")
    end
end

-- Specific functions

function AssetManager:playSFX(name)
    local asset = self:get(name)
    asset:play()
end

-- Activity Functions

function AssetManager:setActivity(isActive)
    self.isActive = isActive
end

function AssetManager:switchActivity()
    self.isActive = (self.isActive == false)
end

function AssetManager:getActivity()
    return self.isActive
end

return AssetManager