package com.humand.demo.modules.IncomingCallMessagingService.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.humand.demo.modules.IncomingCallMessagingService.common.CallPayload
import com.humand.demo.modules.IncomingCallMessagingService.common.Constants
import com.humand.demo.modules.IncomingCallMessagingService.api.BackgroundWorker
import com.humand.demo.modules.IncomingCallMessagingService.cancelNotification

class CallActionReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {

        if (intent.action == Constants.Actions.DECLINE) {
            val payload = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getParcelableExtra(Constants.CALL_PAYLOAD, CallPayload::class.java)
            } else {
                @Suppress("DEPRECATION")
                intent.getParcelableExtra<CallPayload>(Constants.CALL_PAYLOAD)
            }

            // Remove the notification and call api method (reject) with current call_id
            payload?.let {
                val inputData = workDataOf(
                    Constants.CallPayloadKeys.ID to it.id,
                    Constants.CallPayloadKeys.PROVIDER_CALL_ID to it.providerCallId,
                    Constants.CallPayloadKeys.CALLER to it.callerName,
                    Constants.CallPayloadKeys.IS_GROUP to (it.isGroup ?: false),
                    Constants.CallPayloadKeys.INITIALIZATION_CONFIG to it.initializationConfig
                )
                val workRequest = OneTimeWorkRequestBuilder<BackgroundWorker>()
                    .setInputData(inputData)
                    .build()

                WorkManager.getInstance(context).enqueue(workRequest)
            }
            removeNotification(context)
        }
    }

    fun removeNotification(ctx: Context) {
        cancelNotification(ctx)
    }
}
