package com.humand.demo.modules.IncomingCallMessagingService.api

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.humand.demo.modules.CallService.NativeCallsEventObserver
import com.humand.demo.modules.IncomingCallMessagingService.common.Constants
import com.humand.demo.modules.IncomingCallMessagingService.common.hasVideoEnabled

class BackgroundWorker(
    context: Context,
    workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {
    override suspend fun doWork(): Result {
        ApiService.init(applicationContext)
        val callId = inputData.getString(Constants.CallPayloadKeys.ID)
        val callerName = inputData.getString(Constants.CallPayloadKeys.CALLER)
        val isGroup = inputData.getBoolean(Constants.CallPayloadKeys.IS_GROUP, false)
        val initializationConfig = inputData.getString(Constants.CallPayloadKeys.INITIALIZATION_CONFIG)

        return try {
            callId?.let {
                NativeCallsEventObserver.observeCallRejected(
                    callId = it,
                    providerCallId = inputData.getString(Constants.CallPayloadKeys.PROVIDER_CALL_ID) ?: "",
                    cameraEnabled = initializationConfig.hasVideoEnabled(),
                    isGroup = isGroup,
                    caller = callerName
                )
                ApiService.rejectCallSuspend(it)
            }
            Result.success()
        } catch (e: Exception) {
            Result.failure()
        }
    }
}
