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

import okhttp3.Cookie
import okhttp3.HttpUrl

/**
 * 内存 Cookie 存储
 * 
 * 将 Cookie 存储在内存中，应用重启后会丢失
 * 
 * 对应 MVVMHabit 的内存 Cookie 存储
 */
class MemoryCookieStore : CookieStore {
    
    private val cookieMap = mutableMapOf<String, MutableList<Cookie>>()
    
    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
    }
    
    override fun loadCookie(url: HttpUrl): List<Cookie> {
        val host = url.host
        val cookies = cookieMap.getOrDefault(host, mutableListOf())
        
        // 过滤掉过期的 Cookie
        return cookies.filter { it.expiresAt > System.currentTimeMillis() }
    }
    
    override fun clearCookie() {
        cookieMap.clear()
    }
    
    override fun clearCookie(url: HttpUrl) {
        val host = url.host
        cookieMap.remove(host)
    }
}