package com.isidroid.job

import android.content.Context
import androidx.test.platform.app.InstrumentationRegistry
import com.isidroid.job.data.source.local.JobDao
import com.isidroid.job.data.source.local.JobLocalSource
import com.isidroid.job.data.source.remote.JobNetworkSource
import com.isidroid.job.data.source.remote.api.ApiJob
import com.isidroid.job.repository.JobRepositoryImpl
import com.isidroid.test_utils.MockWebServerWrapper
import com.isidroid.test_utils.createApi
import com.isidroid.test_utils.isMethodPost
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config

@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
class TestPrintJob {
    private lateinit var api: ApiJob
    private lateinit var localSource: JobLocalSource
    private lateinit var networkSource: JobNetworkSource
    private lateinit var jobRepository: JobRepositoryImpl
    private lateinit var mockContext: Context
    private lateinit var mockWebServer: MockWebServer

    private val mockWrapper = MockWebServerWrapper { path, method, body ->
        when {
            path == "/api/job" && method.isMethodPost -> "create_job"
            else -> ""
        }
    }

    @Before
    fun setup() {
        val jobDao = mock(JobDao::class.java)
        mockContext = InstrumentationRegistry.getInstrumentation().targetContext
        mockWebServer = mockWrapper.create()
        api = createApi(mockWebServer, ApiJob::class.java)
        networkSource = JobNetworkSource(api)
        localSource = JobLocalSource(jobDao)

        jobRepository = JobRepositoryImpl(networkSource, localSource)
    }


    @After
    fun shutdown() {
        mockWebServer.shutdown()
    }

    @Test
    fun createPrintJob() = runBlocking {
        val job = jobRepository.createJob(
            name = "Hello world",
            clientName = "Client Name",
            printOrientation = 1,
            printSize = 1,
            profileId = "profileId",
            sourceFiles = emptyList(),
            spotId = "spotId"
        )

        Assert.assertEquals("Invalid response parsing", "27", job.id)
    }
}