package com.isidroid.c23.domain.use_case

import android.content.Context
import android.net.Uri
import androidx.documentfile.provider.DocumentFile
import com.isidroid.c23.ext.hasNotificationPermission
import com.isidroid.core.FlowResult
import com.isidroid.rendering.constant.RenderConstant
import com.isidroid.spot.repository.ActiveSpotRepository
import com.isidroid.utils.copyToPublicFolder
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.flow
import java.io.File
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class ContentUseCase @Inject constructor(
    @ApplicationContext private val context: Context,
    private val activeSpotRepository: ActiveSpotRepository
) {
    fun create() = flow {
        val spot = activeSpotRepository.getDefaultSpot()
        val hasNotificationPermission = context.hasNotificationPermission.takeIf { spot != null }

        emit(Pair(spot, hasNotificationPermission))
    }

    fun copyRenderedFilesToPublicFolder(uri: Uri) = flow {
        //
        emit(FlowResult.Loading)
        val files = File(context.cacheDir, RenderConstant.RENDER_FOLDER).listFiles().orEmpty().filter { it.extension == "jpg" }
        val documentFile = DocumentFile.fromTreeUri(context, uri)!!
        var count = 0

        for (file in files) {
            val result = file.copyToPublicFolder(
                context = context,
                targetDisplayName = file.name,
                documentFile = documentFile
            )

            if (result)
                count++
        }

        emit(FlowResult.Success(count))
    }
}