package com.stand.standapp

import android.content.Context
import android.content.SharedPreferences

object AppConfig {
    private const val PREF_NAME = "app_settings"
    private const val KEY_SERVER_URL = "server_url"
    private const val KEY_SERIAL_PORT = "serial_port"
    private const val KEY_REMEMBER_LOGIN = "remember_login"
    private const val KEY_USERNAME = "saved_username"
    private const val KEY_PASSWORD = "saved_password"
    private const val KEY_ACCESS_TOKEN = "access_token"
    
    // 默认配置
    const val DEFAULT_SERVER_URL = "https://template.gyouzhe.com"
    const val DEFAULT_SERIAL_PORT = "ttyACM0"

    private fun getPrefs(context: Context): SharedPreferences {
        return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    }

    fun getServerUrl(context: Context): String {
        return getPrefs(context).getString(KEY_SERVER_URL, DEFAULT_SERVER_URL) ?: DEFAULT_SERVER_URL
    }

    fun setServerUrl(context: Context, url: String) {
        getPrefs(context).edit().putString(KEY_SERVER_URL, url).apply()
    }

    fun getSerialPort(context: Context): String {
        return getPrefs(context).getString(KEY_SERIAL_PORT, DEFAULT_SERIAL_PORT) ?: DEFAULT_SERIAL_PORT
    }

    fun setSerialPort(context: Context, port: String) {
        getPrefs(context).edit().putString(KEY_SERIAL_PORT, port).apply()
    }

    /**
     * 还原默认配置
     */
    fun resetToDefault(context: Context) {
        getPrefs(context).edit()
            .putString(KEY_SERVER_URL, DEFAULT_SERVER_URL)
            .putString(KEY_SERIAL_PORT, DEFAULT_SERIAL_PORT)
            .apply()
    }

    fun isRememberLogin(context: Context): Boolean {
        return getPrefs(context).getBoolean(KEY_REMEMBER_LOGIN, false)
    }

    fun setRememberLogin(context: Context, remember: Boolean) {
        getPrefs(context).edit().putBoolean(KEY_REMEMBER_LOGIN, remember).apply()
    }

    fun getSavedUsername(context: Context): String {
        return getPrefs(context).getString(KEY_USERNAME, "") ?: ""
    }

    fun setSavedUsername(context: Context, username: String) {
        getPrefs(context).edit().putString(KEY_USERNAME, username).apply()
    }

    fun getSavedPassword(context: Context): String {
        return getPrefs(context).getString(KEY_PASSWORD, "") ?: ""
    }

    fun setSavedPassword(context: Context, password: String) {
        getPrefs(context).edit().putString(KEY_PASSWORD, password).apply()
    }

    fun getAccessToken(context: Context): String {
        return getPrefs(context).getString(KEY_ACCESS_TOKEN, "") ?: ""
    }

    fun setAccessToken(context: Context, token: String) {
        getPrefs(context).edit().putString(KEY_ACCESS_TOKEN, token).apply()
    }
}
