package org.zaine.management.data

import android.content.Context
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class SessionStore @Inject constructor(@ApplicationContext context: Context) {
    private val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)

    var token: String?
        get() = prefs.getString("token", null)
        set(value) {
            prefs.edit().putString("token", value).apply()
        }

    var baseUrl: String
        get() = prefs.getString("base_url", DEFAULT_BASE_URL) ?: DEFAULT_BASE_URL
        set(value) {
            prefs.edit().putString("base_url", value.ensureTrailingSlash()).apply()
        }

    fun clear() {
        prefs.edit().remove("token").apply()
    }

    private fun String.ensureTrailingSlash(): String = if (endsWith("/")) this else "$this/"

    companion object {
        private const val DEFAULT_BASE_URL = "http://192.168.0.241:9010/"
    }
}
