package de.storchp.fdroidbuildstatus

import android.content.Context
import android.util.Log
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import de.storchp.fdroidbuildstatus.adapter.db.DbAdapter
import de.storchp.fdroidbuildstatus.adapter.fdroid.FdroidClient
import de.storchp.fdroidbuildstatus.utils.PreferencesService


private val TAG = DownloadFdroidIndexWorker::class.java.simpleName

@HiltWorker
class DownloadFdroidIndexWorker @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted workerParams: WorkerParameters,
    private val preferencesService: PreferencesService,
    private val dbAdapter: DbAdapter,
    private val fdroidClient: FdroidClient,
) : CoroutineWorker(context, workerParams) {

    /**
     * Execute the worker
     */
    override suspend fun doWork(): Result {
        val response = fdroidClient.getIndex()
        if (response.isSuccess) {
            val apps = response.value()!!.apps
            dbAdapter.updateApps(apps)
            preferencesService.setRepoIndexLoaded()
            return Result.success(workDataOf("appsLoaded" to apps.size))
        }
        Log.e(TAG, "Error loading repo index: " + response.errorMessage())
        return Result.failure(workDataOf("errorMessage" to response.errorMessage()))
    }

}
