package com.dphms.optimizer.lite

import android.util.Log
import java.io.BufferedReader
import java.io.InputStreamReader

class OptimizerServiceImpl : IOptimizerService.Stub() {

    companion object { private const val TAG = "DPHMSLiteServiceImpl" }

    override fun executeCommand(command: String): String {
        return try {
            val process = Runtime.getRuntime().exec(arrayOf("sh", "-c", command))
            val reader = BufferedReader(InputStreamReader(process.inputStream))
            val output = StringBuilder()
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                output.appendLine(line)
            }
            process.waitFor()
            output.toString()
        } catch (e: Exception) {
            Log.e(TAG, "Command failed: $command", e)
            "Error: ${e.message}"
        }
    }

    override fun listPackages(): Array<String> {
        val output = executeCommand("pm list packages -3")
        return output.lines()
            .filter { it.startsWith("package:") }
            .map { it.removePrefix("package:").trim() }
            .toTypedArray()
    }

    override fun forceStopPackage(packageName: String): Boolean {
        return try {
            Runtime.getRuntime().exec(arrayOf("sh", "-c", "am force-stop $packageName")).waitFor() == 0
        } catch (e: Exception) { false }
    }

    override fun trimCaches(): Boolean {
        return try {
            Runtime.getRuntime().exec(arrayOf("sh", "-c", "pm trim-caches 999999999999999")).waitFor() == 0
        } catch (e: Exception) { false }
    }
}
