package alraune

import org.w3c.dom.HTMLElement
import vgrechka.*
import kotlin.browser.document
import kotlin.coroutines.experimental.*
import kotlin.js.Promise

class ResolvablePromise<T> {
    var resolve by notNullOnce<(T) -> Unit>()
    var reject by notNullOnce<(Throwable) -> Unit>()

    val promise = Promise<T> {resolve, reject ->
        this.resolve = resolve
        this.reject = reject
    }
}

suspend fun <T> await(p: Promise<T>): T = suspendCoroutine {cont->
    p.then({cont.resume(it)}, {cont.resumeWithException(it)})
}

fun <T> async(block: suspend () -> T): Promise<T> {
    val rep = ResolvablePromise<T>()
    block.startCoroutine(object : Continuation<T> {
        override val context: CoroutineContext get() = EmptyCoroutineContext
        override fun resume(value: T) {rep.resolve(value)}
        override fun resumeWithException(exception: Throwable) {rep.reject(exception)}
    })
    return rep.promise
}

fun elbyid(domid: String): HTMLElement =
    document.getElementById(domid) as HTMLElement? ?: bitch("I want element #$domid")





















