package br.gov.extrema.agenteti.worker

import android.content.Context
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.WorkManager
import br.gov.extrema.agenteti.network.ApiException
import br.gov.extrema.agenteti.repository.AgentRepository
import br.gov.extrema.agenteti.security.SecureStore
import java.util.concurrent.TimeUnit

class InventoryWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
    override fun doWork(): Result = try {
        if (!SecureStore(applicationContext).isActivated()) Result.success()
        else { AgentRepository(applicationContext).sync();Result.success() }
    } catch (error: ApiException) {
        if (error.statusCode == 401 || error.statusCode == 403) Result.failure() else Result.retry()
    } catch (_: Exception) { Result.retry() }
}

object SyncScheduler {
    private const val PERIODIC = "agente-ti-periodic"
    private val network = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
    fun schedule(context: Context) {
        val minutes = SecureStore(context).getInt("sync_interval",30).coerceIn(15,120).toLong()
        val request = PeriodicWorkRequestBuilder<InventoryWorker>(minutes, TimeUnit.MINUTES)
            .setConstraints(network).setBackoffCriteria(BackoffPolicy.EXPONENTIAL,15,TimeUnit.MINUTES).build()
        WorkManager.getInstance(context).enqueueUniquePeriodicWork(PERIODIC,ExistingPeriodicWorkPolicy.UPDATE,request)
    }
    fun now(context: Context) {
        val request=OneTimeWorkRequestBuilder<InventoryWorker>().setConstraints(network).build()
        WorkManager.getInstance(context).enqueueUniqueWork("agente-ti-manual",ExistingWorkPolicy.REPLACE,request)
    }
}
