package dev.privacyllc.period.launcher

import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import dagger.hilt.android.qualifiers.ApplicationContext
import dev.privacyllc.period.MainActivity
import javax.inject.Inject

interface LauncherAliasSwitcher {
    fun setIncognitoEnabled(enabled: Boolean)
}

class AndroidLauncherAliasSwitcher @Inject constructor(
    @ApplicationContext private val context: Context,
) : LauncherAliasSwitcher {

    override fun setIncognitoEnabled(enabled: Boolean) {
        val packageName = context.packageName
        val aliasPackage = MainActivity::class.java.name.substringBeforeLast('.')
        val standard = ComponentName(packageName, "$aliasPackage.PeriodLauncherAlias")
        val incognito = ComponentName(packageName, "$aliasPackage.IncognitoLauncherAlias")

        if (enabled) {
            enable(incognito)
            disable(standard)
        } else {
            enable(standard)
            disable(incognito)
        }
    }

    private fun enable(component: ComponentName) {
        set(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
    }

    private fun disable(component: ComponentName) {
        set(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED)
    }

    private fun set(component: ComponentName, state: Int) {
        context.packageManager.setComponentEnabledSetting(
            component,
            state,
            PackageManager.DONT_KILL_APP,
        )
    }
}
