package com.github.nullptroma.wallenc.ui.screens.main.screens.tasks

import com.github.nullptroma.wallenc.domain.tasks.TaskRunState
import com.github.nullptroma.wallenc.task.runtime.TaskOrchestrator
import com.github.nullptroma.wallenc.ui.resources.UiStringResolver
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config

@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class TaskPipelineViewModelTest {

    @Test
    fun startTestTaskEnqueuesWork() = runBlocking {
        val orchestrator = TaskOrchestrator(Dispatchers.Default)
        val uiStrings = mockk<UiStringResolver>()
        every { uiStrings.invoke(any<Int>(), any()) } returns "Test task"
        every { uiStrings.invoke(any<Int>()) } returns "Test"
        every { uiStrings.plurals(any(), any(), any()) } returns "Plural"
        val viewModel = TaskPipelineViewModel(orchestrator, uiStrings)

        viewModel.startTestTask(durationSec = 0, infinityIndeterminateProgress = false)

        withTimeout(5_000) {
            while (true) {
                val task = orchestrator.pipelineState.value.tasks.singleOrNull()
                if (task?.state is TaskRunState.Completed) break
                delay(25)
            }
        }
        val task = orchestrator.pipelineState.value.tasks.single()
        assertTrue(task.state is TaskRunState.Completed)
    }
}
