sub init()
    m.top.functionName = "run"
end sub

sub run()
    m.top.result = getJson(m.top.url)
end sub

function getJson(url as String) as Object
    xfer = CreateObject("roUrlTransfer")
    port = CreateObject("roMessagePort")
    xfer.SetMessagePort(port)
    xfer.SetUrl(url)
    xfer.SetCertificatesFile("common:/certs/ca-bundle.crt")
    xfer.InitClientCertificates()

    ok = xfer.AsyncGetToString()
    if ok = false then return { success:false, message:"Falha ao iniciar conexão" }

    msg = wait(15000, port)
    if type(msg) = "roUrlEvent" then
        code = msg.GetResponseCode()
        raw = msg.GetString()
        if code < 200 or code >= 300 then return { success:false, message:"HTTP " + code.ToStr() }
        if raw = invalid or raw = "" then return { success:false, message:"Resposta vazia da API" }
        parsed = ParseJson(raw)
        if parsed = invalid then return { success:false, message:"JSON inválido da API" }
        return { success:true, data:parsed }
    end if

    xfer.AsyncCancel()
    return { success:false, message:"Timeout na API" }
end function
