package de.ypchat.android.core

import android.content.Context
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

class SessionCookieJar(context: Context) : CookieJar {
    private val prefs = context.getSharedPreferences("ypchat_cookies", Context.MODE_PRIVATE)

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        val editor = prefs.edit()
        cookies.forEach { cookie ->
            editor.putString(cookie.name, cookie.toString())
        }
        editor.apply()
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        return prefs.all.values
            .mapNotNull { it as? String }
            .mapNotNull { Cookie.parse(url, it) }
            .filter { cookie -> cookie.expiresAt > System.currentTimeMillis() }
    }

    fun clear() {
        prefs.edit().clear().apply()
    }
}
