package com.isidroid.job_sender

import com.isidroid.job.constant.JobStatus
import com.isidroid.job.model.PrintJob
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(index: Int, total: Int) = emit(JobSenderResult.RenderProgress(index, total))
    suspend fun updateProgress(index: Int, total: Int) = emit(JobSenderResult.UploadProgress(index, total))
    suspend fun jobError(jobId: String, t: Throwable) = emit(JobSenderResult.Error(jobId, t))
    suspend fun updateStatus(@JobStatus status: Int, vararg job: PrintJob?) {
        val jobList = job.toList().filterNotNull()
        if (jobList.isNotEmpty())
            emit(JobSenderResult.Statuses(status = status, jobs = jobList))
    }
}