package ext.libsodium.com.ionspin.kotlin.crypto

import com.ionspin.kotlin.crypto.getSodiumLoaded
import com.ionspin.kotlin.crypto.sodiumLoaded
import kotlin.coroutines.suspendCoroutine

/**
 * Created by Ugljesa Jovanovic
 * ugljesa.jovanovic@ionspin.com
 * on 27-May-2020
 */
object JsSodiumLoader {

    suspend fun load(): Unit = suspendCoroutine { continuation ->
        if (!getSodiumLoaded()) {
            JsSodium.default.ready.then<JsAny?> {
                sodiumLoaded = true
                continuation.resumeWith(Result.success(Unit))
                null
            }.catch { e ->
                val throwable = e.toThrowableOrNull()
                if (throwable != null) {
                    continuation.resumeWith(Result.failure(throwable))
                } else {
                    continuation.resumeWith(Result.failure(Throwable("Unknown error", throwable)))
                }
                null
            }
        } else {
            continuation.resumeWith(Result.success(Unit))
        }
    }

    fun loadWithCallback(doneCallback: () -> (Unit)) {
        if (!getSodiumLoaded()) {
            JsSodium.default.ready.then<JsAny?> {
                sodiumLoaded = true
                doneCallback.invoke()
                null
            }
        } else {
            doneCallback.invoke()
        }
    }
}
