--- @class Counter
--- @field private count integer
--- @field private onFinish fun(): nil
--- @field private isAlive boolean
--- @field push fun():nil добавить 1 к счетчику
--- @field pop fun():nil убавить 1 у счетчика
--- @field set fun(count: integer): nil установить значение на счетчике
local counter = {}
counter.__index = counter


--- @private
function counter:_push()
    self.count = self.count + 1
end

--- @private
function counter:_pop()
    self.count = self.count - 1
    if self.count == 0 and self.isAlive then
        self.isAlive = false
        self.onFinish()
    end
end

--- @param onFinish fun(): nil
local function new(onFinish)
    local t = {
        count = 0,
        onFinish = onFinish,
        isAlive = true,
    }
    t.push = function() counter._push(t) end
    t.pop = function() counter._pop(t) end
    t.set = function(count) t.count = count end

    return setmetatable(t, counter)
end

return new
