package com.narutohuo.xindazhou.common.networkrx.cookie

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Cookie
import okhttp3.HttpUrl
import java.util.concurrent.ConcurrentHashMap

/**
 * SharedPreferences Cookie 存储
 * 
 * 将 Cookie 存储在 SharedPreferences 中，应用重启后仍然保留
 * 
 * 对应 MVVMHabit 的持久化 Cookie 存储
 */
class SPCookieStore(private val context: Context) : CookieStore {
    
    private val sp: SharedPreferences = context.getSharedPreferences("cookie_store", Context.MODE_PRIVATE)
    private val gson = Gson()
    private val cookieMap = ConcurrentHashMap<String, MutableList<Cookie>>()
    
    init {
        // 从 SharedPreferences 加载 Cookie
        loadCookiesFromSP()
    }
    
    private fun loadCookiesFromSP() {
        val allCookies = sp.all
        for ((host, cookieJson) in allCookies) {
            if (cookieJson is String) {
                val type = object : TypeToken<MutableList<Cookie>>() {}.type
                val cookies = gson.fromJson<MutableList<Cookie>>(cookieJson, type)
                if (cookies != null) {
                    // 过滤掉过期的 Cookie
                    val validCookies = cookies.filter { it.expiresAt > System.currentTimeMillis() }
                    if (validCookies.isNotEmpty()) {
                        cookieMap[host] = validCookies.toMutableList()
                    } else {
                        // 删除过期的 Cookie
                        sp.edit().remove(host).apply()
                    }
                }
            }
        }
    }
    
    private fun saveCookiesToSP() {
        val editor = sp.edit()
        for ((host, cookies) in cookieMap) {
            val cookieJson = gson.toJson(cookies)
            editor.putString(host, cookieJson)
        }
        editor.apply()
    }
    
    override fun saveCookie(url: HttpUrl, cookies: List<Cookie>) {
        val host = url.host
        val existingCookies = cookieMap.getOrDefault(host, mutableListOf())
        
        // 移除过期的 Cookie
        existingCookies.removeAll { it.expiresAt < System.currentTimeMillis() }
        
        // 添加新的 Cookie
        existingCookies.addAll(cookies)
        cookieMap[host] = existingCookies
        
        // 保存到 SharedPreferences
        saveCookiesToSP()
    }
    
    override fun loadCookie(url: HttpUrl): List<Cookie> {
        val host = url.host
        val cookies = cookieMap.getOrDefault(host, mutableListOf())
        
        // 过滤掉过期的 Cookie
        val validCookies = cookies.filter { it.expiresAt > System.currentTimeMillis() }
        
        // 如果有过期的 Cookie，更新存储
        if (validCookies.size != cookies.size) {
            cookieMap[host] = validCookies.toMutableList()
            saveCookiesToSP()
        }
        
        return validCookies
    }
    
    override fun clearCookie() {
        cookieMap.clear()
        sp.edit().clear().apply()
    }
    
    override fun clearCookie(url: HttpUrl) {
        val host = url.host
        cookieMap.remove(host)
        sp.edit().remove(host).apply()
    }
}