package com.isidroid.c23.domain.use_case

import androidx.compose.ui.graphics.Color
import com.isidroid.c23.domain.dto.PrintJobListItem
import com.isidroid.core.FlowResult
import com.isidroid.job.constant.statusName
import com.isidroid.job.repository.JobRepository
import com.isidroid.rendering.constant.printSizeName
import com.isidroid.spot.repository.SpotRepository
import kotlinx.coroutines.flow.flow
import java.io.File
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class PrintJobsUseCase @Inject constructor(
    private val repository: JobRepository,
    private val spotRepository: SpotRepository
) {
    fun load() = flow {
        emit(FlowResult.Loading)
        val jobList = repository.readLocalList()
        val spots = jobList.map { it.spotId }.distinct().let { spotRepository.findLocalRichSpots(it) }?.associateBy({ it.spot.id }, { it })

        val result = jobList.map { job ->
            val richSpot = spots?.get(job.spotId)
            val profile = richSpot?.printProfiles?.find { it.id == job.profileId }

            PrintJobListItem(
                id = job.id,
                spotName = richSpot?.spot?.name ?: "Deleted spot",
                cost = job.cost,
                paperInfo = job.printSize.printSizeName,
                isColor = profile?.grayscale != true,
                statusColor = Color(0xFF1E88E5),
                comment = job.comment,
                copies = job.copies,
                cover = job.sourceFiles?.firstOrNull()?.takeIf { File(it).exists() },
                statusName = job.status.statusName.lowercase(),
                accessCode = job.accessCode.orEmpty(),
                createdAt = job.createdAt
            )
        }

        emit(FlowResult.Success(result))
    }
}