package com.humand.demo.modules.IncomingCallMessagingService.activity

import android.app.Activity
import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import com.humand.demo.MainActivity
import com.humand.demo.modules.IncomingCallMessagingService.common.CallPayload
import com.humand.demo.modules.IncomingCallMessagingService.common.Constants
import com.humand.demo.modules.IncomingCallMessagingService.cancelNotification

// Close the notification and open App
class AcceptCallActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Enable showing over lock screen
        setShowWhenLocked(true)
        setTurnScreenOn(true)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        // Dismiss the keyguard to allow MainActivity to appear
        val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
        keyguardManager.requestDismissKeyguard(this, null)

        cancelNotification(this)

        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)
        }

        val launchIntent = Intent(this, MainActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or
                    Intent.FLAG_ACTIVITY_SINGLE_TOP or
                    Intent.FLAG_ACTIVITY_CLEAR_TOP
            )
            action = "LAUNCH_INTENT_${payload?.id}"
            putExtra(Constants.CALL_PAYLOAD, payload)
        }

        startActivity(launchIntent)
        finish()
    }
}
