package com.doverfuelingsolutions.issp.utils.sp

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.doverfuelingsolutions.issp.api.WayneApiConfig
import com.doverfuelingsolutions.issp.data.DataStore

object SPUtil {

    private lateinit var sp: SharedPreferences

    fun init(context: Context) {
        sp = PreferenceManager.getDefaultSharedPreferences(context)
        setDefaultValue()
    }

    fun getString(key: String, defaultValue: String = "") = sp.getString(key, defaultValue) ?: ""
    fun putString(key: String, value: String) {
        sp.edit().run {
            putString(key, value)
            apply()
        }
    }

    fun getLong(key: String, defaultValue: Long = 0L) = sp.getLong(key, defaultValue)
    fun putLong(key: String, value: Long) {
        sp.edit().run {
            putLong(key, value)
            apply()
        }
    }


    private fun saveValue(key: String, value: Any) {
        sp.edit().run {
            when (value) {
                is String -> putString(key, value)
                is Long -> putLong(key, value)
            }
            apply()
        }
    }

    private fun setDefaultValue() {
        val firstLaunch = sp.getBoolean(SPKeys.FIRST_LAUNCH, true)
        if (!firstLaunch) return

        sp.edit().run {
            putBoolean(SPKeys.FIRST_LAUNCH, false)

            putString(SPKeys.SN, DataStore.sn)
            putString(SPKeys.SN_RAW, DataStore.snRaw)

            putString(SPKeys.SERVER_DOMAIN, WayneApiConfig.DOMAIN_DEFAULT)
            putString(SPKeys.SERVER_PORT_BASE, WayneApiConfig.PORT_BASE_DEFAULT)
            putString(SPKeys.SERVER_PORT_TRX, WayneApiConfig.PORT_TRX_DEFAULT)
            putString(SPKeys.SERVER_PORT_CONFIG, WayneApiConfig.PORT_CONFIG_DEFAULT)

            putString(SPKeys.MIDDLE_IP, WayneApiConfig.MIDDLE_IP_DEFAULT)
            putString(SPKeys.MIDDLE_PORT, WayneApiConfig.MIDDLE_PORT_DEFAULT)
            putString(SPKeys.MIDDLE_WORKSTATION_ID, WayneApiConfig.MIDDLE_WORKSTATION_ID)

            putString(SPKeys.FUEL_IP, WayneApiConfig.FUEL_IP_DEFAULT)
            putString(SPKeys.FUEL_PORT, WayneApiConfig.FUEL_PORT_DEFAULT)

            commit()
        }
    }
}