package com.isidroid.job_sender

import com.isidroid.job.constant.JobStatus
import com.isidroid.job_sender.domain.dto.JobSenderResult
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.buffer
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class SendJobEventCollectorFlow @Inject constructor() {
    private val _eventsFlow = MutableSharedFlow<JobSenderResult>(replay = 1)
    val eventsFlow = _eventsFlow.asSharedFlow().buffer(capacity = 10)
    private suspend fun emit(result: JobSenderResult) = _eventsFlow.emit(result)
        .also { Timber.i("call: $result") }

    suspend fun renderProgress(jobId: String, index: Int, total: Int) = emit(JobSenderResult.RenderProgress(jobId, index, total))
    suspend fun uploadProgress(jobId: String, index: Int, total: Int) = emit(JobSenderResult.UploadProgress(jobId, index, total))
    suspend fun jobError(jobId: String, t: Throwable) = emit(JobSenderResult.Error(jobId, t))
    suspend fun updateStatus(@JobStatus status: Int, vararg jobIds: String?) = emit(JobSenderResult.Statuses(status = status, jobIds = jobIds.toSet()))

}