package dev.inmo.postssystem.targets.telegram.publication.server

import dev.inmo.micro_utils.mime_types.KnownMimeTypes
import dev.inmo.postssystem.features.content.common.BinaryContent
import dev.inmo.postssystem.features.content.text.common.TextContent
import dev.inmo.postssystem.features.publication.server.PublicationPost
import dev.inmo.postssystem.features.publication.server.PublicationTarget
import dev.inmo.tgbotapi.bot.TelegramBot
import dev.inmo.tgbotapi.extensions.utils.shortcuts.executeUnsafe
import dev.inmo.tgbotapi.requests.abstracts.asMultipartFile
import dev.inmo.tgbotapi.requests.send.SendTextMessage
import dev.inmo.tgbotapi.requests.send.media.*
import dev.inmo.tgbotapi.types.ChatId
import dev.inmo.tgbotapi.utils.StorageFile
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.core.readBytes
import kotlinx.coroutines.delay

class PublicationTargetTelegram(
    private val bot: TelegramBot,
    private val targetChatId: ChatId
) : PublicationTarget {
    override suspend fun publish(post: PublicationPost) {
        post.content.mapNotNull {
            val content = it.content
            when (content) {
                is BinaryContent -> {
                    val storageFile by lazy {
                        StorageFile(content.filename.name, content.inputProvider().readBytes()).asMultipartFile()
                    }
                    when (content.mimeType) {
                        is KnownMimeTypes.Image.Jpeg,
                        is KnownMimeTypes.Image.Png -> {
                            SendPhoto(targetChatId, storageFile)
                        }
                        is KnownMimeTypes.Video.Mp4 -> {
                            SendVideo(targetChatId, storageFile)
                        }
                        is KnownMimeTypes.Audio.Mpeg -> {
                            SendAudio(targetChatId, storageFile)
                        }
                        else -> null
                    }
                }
                is TextContent -> {
                    SendTextMessage(targetChatId, content.text)
                }
                else -> null
            }
        }.forEach { request ->
            bot.executeUnsafe(request, 3, 1000L)
            delay(100L)
        }
    }
}
