local task = require "lib.utils.task"

local test = {}

local t0
local task1Start, task2Start
local task1Callback, task2Callback

--- @return Task<number>
local function task1()
    return function(callback)
        task1Start = love.timer.getTime()
        task1Callback = callback
    end
end

--- @return Task<number>
local function task2()
    return function(callback)
        task2Start = love.timer.getTime()
        task2Callback = callback
    end
end

function test:run(complete)
    t0 = love.timer.getTime()

    task.wait {
        task1(),
        task2()
    } (function(values)
            local tWait = love.timer.getTime()
            local dt = tWait - t0

            local t1 = values[1]
            local t2 = values[2]

            assert(type(t1) == "number" and type(t2) == "number")
            assert(t2 > t1)
            assert(dt >= 2, "dt = " .. dt)

            print("task.wait completed in " .. dt .. " sec", "t1 = " .. t1 - t0, "t2 = " .. t2 - t0)


            t0 = love.timer.getTime()
            task.chain(task1(), function(value)
                t1 = value
                assert(t1 - t0 >= 1)
                return task2()
            end)(
                    function(value)
                        t2 = value
                        assert(t2 - t0 >= 2)
                        print("task.chain completed in " .. t2 - t0 .. " sec")

                        complete()
                    end
                )
        end)
end

function test:update(dt)
    local t = love.timer.getTime()
    if task1Start and t - task1Start >= 1 then
        task1Callback(t)
        task1Start = nil
    end

    if task2Start and t - task2Start >= 2 then
        task2Callback(t)
        task2Start = nil
    end
end

return test
