package com.isidroid.c23.domain.use_case

import android.content.Context
import com.isidroid.c23.data.source.local.AppDataBase
import com.isidroid.job_sender.SendJobWorker
import com.isidroid.c23.ext.isDebug
import com.isidroid.c23.ui.screen.home.HomeContract
import com.isidroid.core.DiMock
import com.isidroid.core.FlowResult
import com.isidroid.session.repository.SessionRepository
import com.isidroid.spot.repository.ActiveSpotRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class HomeUseCase @Inject constructor(
    @ApplicationContext private val context: Context,
    private val sessionRepository: SessionRepository,
    private val activeSpotRepository: ActiveSpotRepository,
    private val appDataBase: AppDataBase
) {
    fun createSession() = flow {
        emit(FlowResult.Loading)

//        if (isDebug()) {
//            appDataBase.clearAllTables()
//        }


        SendJobWorker.create(context)

        val maxDelay = if (isDebug()) 0 else 3_000
        val startedAt = System.currentTimeMillis()

        val hasSession = sessionRepository.hasCurrent
        val hasDefaultSpot = activeSpotRepository.getDefaultSpot() != null

        val ts = System.currentTimeMillis() - startedAt

        val navigation = when {
            !hasSession -> HomeContract.Effect.Navigation.ToLogin
            !hasDefaultSpot -> HomeContract.Effect.Navigation.ToSelectSpot(
                lat = 38.8870757,
                lng = -94.6933749


//                lat = 37.2451678,
//                lng = -121.9752617,
            )


            else -> HomeContract.Effect.Navigation.ToSelectContent
        }

        val delay = maxDelay - ts
        delay(delay)

        emit(FlowResult.Success(navigation))
    }
}
