package com.idea.gametime.session

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.lang.ref.WeakReference

object SessionNotificationPlugin {
    private const val METHOD_CHANNEL = "gametime.session_notification/methods"
    private const val NOTIFICATION_PERMISSION_REQUEST_CODE = 9210

    private var appContext: Context? = null
    private var activityRef: WeakReference<Activity>? = null
    private var notificationPermissionRequested = false

    fun register(flutterEngine: FlutterEngine, activity: Activity) {
        appContext = activity.applicationContext
        activityRef = WeakReference(activity)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, METHOD_CHANNEL)
            .setMethodCallHandler(::handleMethodCall)
    }

    private fun handleMethodCall(call: MethodCall, result: MethodChannel.Result) {
        val context = appContext
        if (context == null) {
            result.error("session_notification_unavailable", "Application context unavailable.", null)
            return
        }
        when (call.method) {
            "show" -> show(context, call.arguments, result)
            "clear" -> {
                context.stopService(Intent(context, SessionStatusForegroundService::class.java))
                result.success(null)
            }
            else -> result.notImplemented()
        }
    }

    private fun show(context: Context, arguments: Any?, result: MethodChannel.Result) {
        val map = arguments as? Map<*, *>
        if (map == null) {
            result.error("invalid_notification", "Notification payload must be a map.", null)
            return
        }
        requestPostNotificationsPermissionIfNeeded()
        val intent = Intent(context, SessionStatusForegroundService::class.java).apply {
            action = SessionStatusForegroundService.ACTION_SHOW
            putExtra(SessionStatusForegroundService.EXTRA_TITLE, map["title"] as? String ?: "GameTime")
            putExtra(
                SessionStatusForegroundService.EXTRA_PRIMARY_LINE,
                map["primaryLine"] as? String ?: "Séance en cours",
            )
            putExtra(
                SessionStatusForegroundService.EXTRA_SECONDARY_LINE,
                map["secondaryLine"] as? String,
            )
        }
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            context.startForegroundService(intent)
        } else {
            context.startService(intent)
        }
        result.success(null)
    }

    private fun requestPostNotificationsPermissionIfNeeded() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
            notificationPermissionRequested
        ) {
            return
        }
        val activity = activityRef?.get() ?: return
        if (activity.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) ==
            PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        notificationPermissionRequested = true
        activity.requestPermissions(
            arrayOf(Manifest.permission.POST_NOTIFICATIONS),
            NOTIFICATION_PERMISSION_REQUEST_CODE,
        )
    }
}
