#include "../config/events.lua"
#include "helpers/string.lua"

function init()
    effectsActive = {}
    RegisterListenerTo(EVENTS.UI_EFFECT, "UIEffect")
end

function UIEffect(data)
    local effect, parameters = data:match("([%w_]+);?(.*)")
    if effectsActive[effect] then
        effectsActive[effect] = nil
        return
    end
    effectsActive[effect] = parameters:as_map("([^=;]+)=?([^;]*)")
    effectsActive[effect].__transition = nil
end

local effects = {
    fade = function(self, dt)
        if self.delay then
            self.delay = self.delay - dt
            if self.delay <= dt then
                self.delay = nil
            end
            return
        end
        if not self.__transition then
            self.__transition = 0
            local t
            if self.pre then
                t = self.duration * self.pre
            else
                t = self.duration/2
            end
            SetValueInTable(self, "__transition", 1, "linear", t)
        elseif self.__transition == 1 then
            local t
            if self.post then
                t = self.duration * self.post
            else
                t = self.duration/2
            end
            SetValueInTable(self, "__transition", 0, "linear", t)
        elseif self.__transition == 0 then
            return true
        end
		UiColor(0, 0, 0, self.__transition)
		UiRect(UiWidth(), UiHeight())
    end,
}

function draw(dt)
    local to_remove
    for k, v in pairs(effectsActive) do
        UiPush()
            if effects[k](v, dt) then
                if to_remove then to_remove[#to_remove+1] = k else to_remove = { k } end
            end
        UiPop()
    end
    if to_remove then
        for i = 1, #to_remove do effectsActive[to_remove[i]] = nil end
    end
end
