package dev.inmo.postssystem.features.common.common

import dev.inmo.micro_utils.common.MPPFile
import io.ktor.utils.io.core.*
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.ByteArraySerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.Serializable

@Serializable(SimpleInputProviderSerializer::class)
interface SimpleInputProvider {
    operator fun invoke(): Input
}

@Serializable
class BytesBasedInputProvider(
    private val bytes: ByteArray
) : SimpleInputProvider {
    override fun invoke(): Input {
        return ByteReadPacket(bytes)
    }
}

@Serializable(SimpleInputProviderSerializer::class)
expect class FileBasedInputProvider : SimpleInputProvider {
    val file: MPPFile
}

object SimpleInputProviderSerializer : KSerializer<SimpleInputProvider> {
    private val serializer = ByteArraySerializer()
    override val descriptor: SerialDescriptor
        get() = serializer.descriptor
    override fun deserialize(decoder: Decoder): SimpleInputProvider {
        val bytes = serializer.deserialize(decoder)
        return BytesBasedInputProvider(bytes)
    }

    override fun serialize(encoder: Encoder, value: SimpleInputProvider) {
        serializer.serialize(
            encoder,
            value().readBytes()
        )
    }

}
