package eu.mhsl.marianum.mobile.client

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 widgetChannel = "eu.mhsl.marianum.widget"
    /// Last seen widget tap target. Cleared by Dart via `consumePendingNavigation`
    /// so the same intent isn't replayed on every resume.
    private var pendingTimetableTap: Boolean = false

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            widgetChannel
        ).setMethodCallHandler { call, result ->
            when (call.method) {
                "consumePendingNavigation" -> {
                    val pending = pendingTimetableTap
                    pendingTimetableTap = false
                    result.success(pending)
                }
                else -> result.notImplemented()
            }
        }
        consumeIntentData(intent)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        consumeIntentData(intent)
    }

    private fun consumeIntentData(intent: Intent?) {
        if (intent?.getBooleanExtra("widget_open_timetable", false) == true) {
            pendingTimetableTap = true
        }
    }
}
