package com.example.smart119
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

object MyCookieJar : CookieJar {

    private val cookieStore: MutableMap<String, MutableList<Cookie>> = mutableMapOf()
    private val cookieCustom: MutableMap<String, String> = mutableMapOf()

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        val host = url.url().host // URL의 호스트 이름 추출
        if (cookies.isNotEmpty()) {
            cookieStore[host] = cookies.toMutableList()
        }
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        val host = url.url().host
        return cookieStore[host] ?: mutableListOf()
    }
    fun setCookie(cookie:String) {
        var cookieSplits = cookie.split("=")
//        println(cookieSplits[0])
//        println(cookieSplits[1])
        cookieCustom.put(cookieSplits[0], cookie)
    }
    fun getCustomCookies():MutableList<String> {
        var retList:MutableList<String> = mutableListOf()
        cookieCustom.forEach { key, value ->
            retList.add(value)
        }

        return retList;
    }
    fun getAllCookies():List<Cookie> {
        return cookieStore.values.flatten()
    }


    // 쿠키 상태 확인 (디버깅용)
    fun getCookies(): Map<String, List<Cookie>> {
        return cookieStore
    }

    // 모든 쿠키 삭제
    fun clearCookies() {
        cookieStore.clear()
    }


}