package com.tsmobile.app.data

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

// Context 扩展属性
private val Context.recentConnectionsDataStore: DataStore<Preferences>
    by preferencesDataStore(name = "recent_connections")

class RecentConnectionsStore(private val context: Context) {

    companion object {
        private const val MAX_RECENT = 3
        private val RECENTS_KEY = stringPreferencesKey("recents_json")
    }

    /**
     * 观察最近连接列表（按 lastConnectedAt 倒序）。
     */
    fun observeRecents(): Flow<List<RecentConnection>> {
        return context.recentConnectionsDataStore.data.map { prefs ->
            val json = prefs[RECENTS_KEY] ?: return@map emptyList()
            try {
                Json.decodeFromString<List<RecentConnection>>(json)
                    .sortedByDescending { it.lastConnectedAt }
            } catch (_: Exception) {
                emptyList()
            }
        }
    }

    /**
     * 记录一次连接（成功或失败）。
     * 相同 address + nickname 去重，保留最新记录。
     */
    suspend fun addRecent(recent: RecentConnection) {
        context.recentConnectionsDataStore.edit { prefs ->
            val current = try {
                Json.decodeFromString<List<RecentConnection>>(prefs[RECENTS_KEY] ?: "[]")
            } catch (_: Exception) {
                emptyList()
            }.toMutableList()

            // 去重：移除相同 address + nickname 的旧记录
            current.removeAll { it.address == recent.address && it.nickname == recent.nickname }
            current.add(0, recent) // 插入到头部

            // 限制最多 MAX_RECENT 条
            val trimmed = current.take(MAX_RECENT)
            prefs[RECENTS_KEY] = Json.encodeToString(trimmed)
        }
    }

    /**
     * 删除单条记录。
     */
    suspend fun removeRecent(address: String, nickname: String) {
        context.recentConnectionsDataStore.edit { prefs ->
            val current = try {
                Json.decodeFromString<List<RecentConnection>>(prefs[RECENTS_KEY] ?: "[]")
            } catch (_: Exception) {
                emptyList()
            }.toMutableList()

            current.removeAll { it.address == address && it.nickname == nickname }
            prefs[RECENTS_KEY] = Json.encodeToString(current)
        }
    }

    /**
     * 清空所有记录。
     */
    suspend fun clearAll() {
        context.recentConnectionsDataStore.edit { prefs ->
            prefs.remove(RECENTS_KEY)
        }
    }
}
