package com.github.nullptroma.wallenc.app.tasks

import android.content.Context
import android.content.Intent
import androidx.core.content.ContextCompat
import com.github.nullptroma.wallenc.domain.tasks.ITaskOrchestrator
import com.github.nullptroma.wallenc.domain.tasks.TaskForegroundUiState
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class TaskPipelineForegroundBootstrap @Inject constructor(
    @param:ApplicationContext private val app: Context,
    private val orchestrator: ITaskOrchestrator,
) {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

    fun start() {
        scope.launch {
            orchestrator.foregroundUi
                .map { it is TaskForegroundUiState.Visible }
                .distinctUntilChanged()
                .filter { visible -> visible }
                .collect {
                    ContextCompat.startForegroundService(
                        app,
                        Intent(app, TaskPipelineForegroundService::class.java),
                    )
                }
        }
    }
}
