package dev.inmo.postssystem.client.utils

import androidx.compose.runtime.MutableState
import dev.inmo.postssystem.features.files.common.FullFileInfo
import dev.inmo.micro_utils.common.*
import dev.inmo.micro_utils.mime_types.KnownMimeTypes
import dev.inmo.micro_utils.mime_types.findBuiltinMimeType
import io.ktor.utils.io.core.ByteReadPacket
import kotlinx.coroutines.flow.MutableStateFlow
import org.khronos.webgl.ArrayBuffer
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event
import org.w3c.files.FileReader
import org.w3c.files.get

fun uploadFileCallbackForHTMLInputChange(
    onSet: (FullFileInfo) -> Unit
): (Event) -> Unit = {
    (it.target as? HTMLInputElement) ?.apply {
        files ?.also { files ->
            files[0] ?.also { file ->
                val reader: FileReader = FileReader()

                reader.onload = {
                    val bytes = ((it.target.asDynamic()).result as ArrayBuffer).toByteArray()
                    onSet(
                        FullFileInfo(
                            FileName(file.name),
                            findBuiltinMimeType(file.type) ?: KnownMimeTypes.Any,
                        ) {
                            ByteReadPacket(bytes)
                        }
                    )
                }

                reader.readAsArrayBuffer(file)
            }
        }
    }
}

fun fileCallbackForHTMLInputChange(
    onSet: (MPPFile) -> Unit
): (Event) -> Unit = {
    (it.target as? HTMLInputElement) ?.apply {
        files ?.also { files ->
            files[0] ?.also { file ->
                onSet(file)
            }
        }
    }
}

fun uploadFileCallbackForHTMLInputChange(
    output: MutableState<FullFileInfo?>
): (Event) -> Unit = uploadFileCallbackForHTMLInputChange {
    output.value = it
}

fun uploadFileCallbackForHTMLInputChange(
    output: MutableStateFlow<FullFileInfo?>
): (Event) -> Unit = uploadFileCallbackForHTMLInputChange {
    output.value = it
}

fun fileCallbackForHTMLInputChange(
    output: MutableState<MPPFile?>
): (Event) -> Unit = fileCallbackForHTMLInputChange {
    output.value = it
}

fun fileCallbackForHTMLInputChange(
    output: MutableStateFlow<MPPFile?>
): (Event) -> Unit = fileCallbackForHTMLInputChange {
    output.value = it
}

