package com.yorvana.testsupport

import androidx.test.platform.app.InstrumentationRegistry
import java.io.FileInputStream

object DemoMode {
    private var originalNavMode: String? = null

    fun enter() {
        runShell("cmd uimode night no")

        // Capture original state before modifying
        originalNavMode = runShell("settings get secure navigation_mode").trim()

        // Force Gesture Navigation via settings and overlay
        runShell("settings put secure navigation_mode 2")
        runShell("cmd overlay enable com.android.internal.systemui.navbar.gestural")

        runShell("settings put global sysui_demo_allowed 1")
        runShell("am broadcast -a com.android.systemui.demo -e command enter")
        runShell("am broadcast -a com.android.systemui.demo -e command clock -e hhmm 0900")
        runShell("am broadcast -a com.android.systemui.demo -e command battery -e level 100 -e plugged false")
        runShell("am broadcast -a com.android.systemui.demo -e command network -e wifi show -e level 4")
        runShell("am broadcast -a com.android.systemui.demo -e command network -e mobile show -e datatype none -e level 4")
        runShell("am broadcast -a com.android.systemui.demo -e command notifications -e visible false")

        // Poll for gesture navigation to be active (max 5s)
        var settled = false
        for (i in 0..50) {
            val mode = runShell("settings get secure navigation_mode").trim()
            if (mode == "2") {
                settled = true
                break
            }
            Thread.sleep(100)
        }
        if (!settled) {
            android.util.Log.w("DemoMode", "Navigation mode failed to settle on '2' (gesture)")
        }
        // Small extra delay for SystemUI animations to finish
        Thread.sleep(500)
    }

    fun exit() {
        val capturedMode = originalNavMode?.trim()
        val restoreMode = if (capturedMode !in setOf("0", "1", "2")) "0" else capturedMode!!

        if (restoreMode == "2") {
            runShell("cmd overlay enable com.android.internal.systemui.navbar.gestural")
        } else {
            runShell("cmd overlay enable com.android.internal.systemui.navbar.threebutton")
        }
        runShell("settings put secure navigation_mode $restoreMode")
        runShell("am broadcast -a com.android.systemui.demo -e command exit")
    }

    fun ensureOutputDirectory() {
        runShell("mkdir -p ${ScreenshotConstants.DEVICE_SCREENSHOT_DIR}")
    }

    fun runShell(command: String): String {
        val automation = InstrumentationRegistry.getInstrumentation().uiAutomation
        val descriptor = automation.executeShellCommand(command)
        return try {
            FileInputStream(descriptor.fileDescriptor)
                .use { it.readBytes() }
                .toString(Charsets.UTF_8)
        } finally {
            descriptor.close()
        }
    }
}
