package xyz.myachin.saveto.settings

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import androidx.preference.PreferenceManager
import xyz.myachin.saveto.ui.MainActivity

object Settings {
    private const val settings_version = "settings_version"
    private const val use_downloader = "use_downloader"
    private const val text_length = "text_file_name_length"
    private const val hide_launcher_icon = "hide_launcher_icon"

    private var mEditor: SharedPreferences.Editor? = null
    private lateinit var mPrefs: SharedPreferences

    fun setup(context: Context) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(context)
    }

    private val editor: SharedPreferences.Editor
        @SuppressLint("CommitPrefEdits")
        get() {
            mEditor?.run {
                return this
            }
            mEditor = mPrefs.edit()
            return mEditor!!
        }

    var textLength: Int
        get() = mPrefs.getInt(text_length, 5)
        set(value) {
            editor.putInt(text_length, value)
            editor.apply()
        }

    var useDownloader: Boolean
        get() = mPrefs.getBoolean(use_downloader, true)
        set(value) {
            editor.putBoolean(use_downloader, value)
            editor.apply()
        }

    var hideLauncherIcon: Boolean
        get() = mPrefs.getBoolean(hide_launcher_icon, false)
        set(value) {
            editor.putBoolean(hide_launcher_icon, value)
            editor.apply()
        }

    var versionSettings: String
        get() = mPrefs.getString(settings_version, "")!!
        set(value) {
            editor.putString(settings_version, value)
            editor.apply()
        }


    fun setLauncherIconState(context: Context, state: Int) {
        val cmp = ComponentName.createRelative(context, MainActivity::class.java.name)
        context.packageManager.setComponentEnabledSetting(cmp, state, PackageManager.DONT_KILL_APP)
    }
}
