#!/bin/sh

set -eu

lua -v 2>&1

# The demo below is based on examples/demo.lua, with a fix applied.
cat > /tmp/promise-async-demo.lua <<'LUA'
---@diagnostic disable: unused-local
local uv = require('luv')
local async = require('async')
local promise = require('promise')

math.randomseed(math.ceil(uv.uptime()))

local function setTimeout(callback, ms)
    local timer = uv.new_timer()
    timer:start(ms, 0, function()
        timer:close()
        callback()
    end)
    return timer
end

local function defuse(ms)
    return promise:new(function(resolve, reject)
        setTimeout(function()
            resolve(ms)
        end, ms)
    end)
end

local function bomb(ms)
    return promise(function(resolve, reject)
        setTimeout(function()
            reject(ms)
        end, ms)
    end)
end

local function race()
    return async(function()
        return promise.race({
            defuse(math.random(500, 1000)),
            bomb(math.random(800, 1000))
        })
    end)
end

local notify = vim and vim.notify or print

local function play()
    return async(function()
        notify('Game start!')

        local cnt = 0

        xpcall(function()
            while true do
                local ms = await(race())
                cnt = cnt + ms
                notify(('Defuse after %dms~'):format(ms))
            end
        end, function(msErr)
            cnt = cnt + msErr
            notify(('Bomb after %dms~'):format(msErr))
        end)

        notify(('Game end after %dms!'):format(cnt))

        local ok, err = pcall(function()
            await {
                thenCall = function(self, resolve, reject)
                    setTimeout(function()
                        reject(self.message)
                    end, 1000)
                end,
                message = 'try to throw an error :)'
            }
        end)

        if not ok then
            notify(('Caught expected error: %s'):format(err))
        end
    end)
end

promise.resolve():thenCall(function(value)
    notify('In next tick')
end)

notify('In main')

play():finally(function()
    print('Game finished!')
end)

if not vim then
    uv.run()
end
LUA

lua /tmp/promise-async-demo.lua
