package com.fastest.pass.helpers

import android.content.Context
import com.fastest.pass.login.data.model.UserInfo
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class BasePreferenceHelper(private val context: Context) : PreferencesHelper() {

    fun clearAllData() {
        removePreference(context, KEY_FILENAME, KEY_IS_LOGGED_IN)
        removePreference(context, KEY_FILENAME, KEY_BEARER_TOKEN)
        removePreference(context, KEY_FILENAME, KEY_USERINFO)
        removePreference(context, KEY_FILENAME, KEY_SALT_KEY)
    }

    fun setLoggedInState(state: Boolean) {
        putBooleanPreference(context, KEY_FILENAME, KEY_IS_LOGGED_IN, state)
    }

    fun getLoggedInState(): Boolean {
        return getBooleanPreference(context, KEY_FILENAME, KEY_IS_LOGGED_IN)
    }

    fun saveToken(token: String) {
        putStringPreference(context, KEY_FILENAME, KEY_BEARER_TOKEN, token)
    }

    fun getToken(): String? {
        return getStringPreference(context, KEY_FILENAME, KEY_BEARER_TOKEN)
    }

    fun saveUserInfo(userInfo: UserInfo?) {
        putStringPreference(context, KEY_FILENAME, KEY_USERINFO, Gson().toJson(userInfo))
    }

    fun getUserInfo() : UserInfo? {
        val type = object : TypeToken<UserInfo?>() {}.type
        return Gson().fromJson<UserInfo?>(
            getStringPreference(
                context, KEY_FILENAME, KEY_USERINFO
            ), type
        )
    }

    fun saveCustomSaltKey(saltKey: String) {
        putStringPreference(context, KEY_FILENAME, KEY_SALT_KEY, saltKey)
    }

    fun getCustomSaltKey(): String? {
        return getStringPreference(context, KEY_FILENAME, KEY_SALT_KEY)
    }

    companion object {
        private const val KEY_FILENAME = "file_fastestpass"
        private const val KEY_IS_LOGGED_IN = "key_isloggedin"
        private const val KEY_BEARER_TOKEN = "key_bearer_token"
        private const val KEY_USERINFO = "key_userinfo"
        private const val KEY_SALT_KEY = "key_salt_key"
    }
}