package com.dronex.rec.recording

import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.dronex.rec.AppConstants
import com.dronex.rec.MainActivity
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class RecordingPlatformHandler(
        private val activity: MainActivity,
        messenger: BinaryMessenger,
) : MethodChannel.MethodCallHandler {
    private val methodChannel = MethodChannel(messenger, AppConstants.RECORDING_METHOD_CHANNEL)

    init {
        methodChannel.setMethodCallHandler(this)
    }

    fun dispose() {
        methodChannel.setMethodCallHandler(null)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "hasNotificationPolicyAccess" -> result.success(DoNotDisturbHelper.hasAccess(activity))
            "openNotificationPolicySettings" -> {
                DoNotDisturbHelper.openAccessSettings(activity)
                result.success(null)
            }
            "enableDoNotDisturb" -> result.success(DoNotDisturbHelper.enable(activity))
            "disableDoNotDisturb" -> {
                DoNotDisturbHelper.disable(activity)
                result.success(null)
            }
            "isIgnoringBatteryOptimizations" ->
                    result.success(BatteryOptimizationHelper.isIgnoringOptimizations(activity))
            "openBatteryOptimizationSettings" -> {
                BatteryOptimizationHelper.openSettings(activity)
                result.success(null)
            }
            "setImmersiveMode" -> {
                val enabled = call.argument<Boolean>("enabled") ?: false
                setImmersiveMode(enabled)
                result.success(null)
            }
            "isForegroundServiceRunning" -> result.success(RecordingForegroundService.isRunning)
            else -> result.notImplemented()
        }
    }

    private fun setImmersiveMode(enabled: Boolean) {
        val window = activity.window
        WindowCompat.setDecorFitsSystemWindows(window, !enabled)
        val insetsController = WindowInsetsControllerCompat(window, window.decorView)
        if (enabled) {
            insetsController.hide(WindowInsetsCompat.Type.systemBars())
            insetsController.systemBarsBehavior =
                    WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        } else {
            insetsController.show(WindowInsetsCompat.Type.systemBars())
        }
    }
}
