package dev.inmo.postssystem.services.posts.client

import dev.inmo.micro_utils.common.MPPFile
import dev.inmo.micro_utils.ktor.client.UnifiedRequester
import dev.inmo.postssystem.features.files.common.FileId
import kotlinx.coroutines.*
import kotlinx.coroutines.GlobalScope.coroutineContext
import org.w3c.xhr.*

internal actual suspend fun UnifiedRequester.tempUpload(
    fullTempUploadDraftPath: String,
    file: MPPFile,
    onUpload: (Long, Long) -> Unit
): FileId {
    val formData = FormData()
    val answer = CompletableDeferred<FileId>()

    formData.append(
        "data",
        file
    )

    val request = XMLHttpRequest()
    request.responseType = XMLHttpRequestResponseType.TEXT
    request.upload.onprogress = {
        onUpload(it.loaded.toLong(), it.total.toLong())
    }
    request.onload = {
        if (request.status == 200.toShort()) {
            answer.complete(FileId(request.responseText))
        } else {
            answer.completeExceptionally(Exception("Something went wrong"))
        }
    }
    request.onerror = {
        answer.completeExceptionally(Exception("Something went wrong"))
    }
    request.open("POST", fullTempUploadDraftPath, true)
    request.send(formData)

    currentCoroutineContext().job.invokeOnCompletion {
        runCatching {
            request.abort()
        }
    }

    return answer.await()
}

