package com.joe.camera.webcam.system

import android.os.Build
import android.os.IBinder

/** Equivalent of the reference project's DisplayToggle.dex, embedded in the APK. */
object DisplayToggle {
    fun setDisplayPowerMode(mode: Int): Boolean = runCatching {
        val surfaceControl = Class.forName("android.view.SurfaceControl")
        val displayToken = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            surfaceControl.getMethod("getInternalDisplayToken").invoke(null) as IBinder
        } else {
            surfaceControl.getMethod("getBuiltInDisplay", Int::class.javaPrimitiveType).invoke(null, 0) as IBinder
        }
        surfaceControl
            .getMethod("setDisplayPowerMode", IBinder::class.java, Int::class.javaPrimitiveType)
            .invoke(null, displayToken, mode)
        true
    }.getOrDefault(false)

    @JvmStatic
    fun main(args: Array<String>) {
        val mode = args.firstOrNull()?.toIntOrNull() ?: return
        if (!setDisplayPowerMode(mode)) throw IllegalStateException("Unable to set display power mode")
    }
}
