package org.fnives.flutter.experiment_shorebird

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Process

const val KEY_ORIGINAL_PID = "KEY_ORIGINAL_PID"
const val KEY_INTENT = "KEY_INTENT"

class RestartActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        Process.killProcess(intent.getIntExtra(KEY_ORIGINAL_PID, -1))

        val intent = if (Build.VERSION.SDK_INT > 33) {
            intent.getParcelableExtra(KEY_INTENT, Intent::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableExtra(KEY_INTENT)
        }

        startActivity(intent)
        finish()
    }

    companion object {
        fun restart(context: Context, intent: Intent) {
            val restartIntent = Intent(context, RestartActivity::class.java)
            restartIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
            restartIntent.putExtra(KEY_ORIGINAL_PID, Process.myPid())
            restartIntent.putExtra(KEY_INTENT, intent)
            context.startActivity(restartIntent)
        }
    }
}