package org.fnives.flutter.experiment_shorebird

import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Intent
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel


class MainActivity : FlutterActivity() {
    private val channel = "MainChannel"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            channel
        ).setMethodCallHandler { call, result ->
            when (call.method) {
                Methods.RESTART.methodName -> {
                    val pendingIntent = PendingIntent.getActivity(
                        context,
                        4201,
                        if (isHomeApp()) Intent(intent.action).apply {
                            flags = Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
                            intent.categories.forEach {
                                addCategory(it)
                            }
                        } else Intent(this, this::class.java).apply {
                            flags = Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
                        },
                        PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
                    )
                    val alarmManager = context.getSystemService(ALARM_SERVICE) as AlarmManager
                    alarmManager[AlarmManager.RTC, System.currentTimeMillis() + 100] =
                        pendingIntent
                    if (context is Activity) {
                        (context as Activity).finishAndRemoveTask()
                    }
                    Runtime.getRuntime().exit(0)
                    result.success(Unit)
                }
            }
        }
    }

    private fun isHomeApp(): Boolean {
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_HOME)
        val res = packageManager.resolveActivity(intent, 0)
        return res?.activityInfo != null && (packageName == res.activityInfo.packageName)
    }
}
