package xyz.kusoft.argusupdater

import android.content.Context

class ArgusUpdatePreferences(context: Context) {
    private val preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

    fun loadLastInstallerEvent(): ArgusInstallerEvent? {
        val state = preferences.getString(KEY_INSTALLER_STATE, null) ?: return null
        return ArgusInstallerEvent(
            state = state,
            packageName = preferences.getString(KEY_PACKAGE_NAME, null),
            releaseVersion = preferences.getString(KEY_RELEASE_VERSION, null),
            versionCode = if (preferences.contains(KEY_VERSION_CODE)) {
                preferences.getLong(KEY_VERSION_CODE, 0L)
            } else {
                null
            },
            detail = preferences.getString(KEY_DETAIL, null),
            updatedAtEpochMillis = preferences.getLong(KEY_UPDATED_AT, 0L)
        )
    }

    fun saveInstallerEvent(
        state: String,
        packageName: String?,
        releaseVersion: String?,
        versionCode: Long?,
        detail: String?,
        updatedAtEpochMillis: Long = System.currentTimeMillis()
    ) {
        preferences.edit()
            .putString(KEY_INSTALLER_STATE, state)
            .putString(KEY_PACKAGE_NAME, packageName)
            .putString(KEY_RELEASE_VERSION, releaseVersion)
            .putString(KEY_DETAIL, detail)
            .putLong(KEY_UPDATED_AT, updatedAtEpochMillis)
            .apply {
                if (versionCode == null) {
                    remove(KEY_VERSION_CODE)
                } else {
                    putLong(KEY_VERSION_CODE, versionCode)
                }
            }
            .apply()
    }

    private companion object {
        const val PREFS_NAME = "argus-updater"
        const val KEY_INSTALLER_STATE = "installer_state"
        const val KEY_PACKAGE_NAME = "package_name"
        const val KEY_RELEASE_VERSION = "release_version"
        const val KEY_VERSION_CODE = "version_code"
        const val KEY_DETAIL = "detail"
        const val KEY_UPDATED_AT = "updated_at"
    }
}
