package com.swoosh.microblog.data

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.swoosh.microblog.data.model.GhostSite

class SiteMetadataCache(context: Context) {

    private val prefs: SharedPreferences = context.getSharedPreferences(
        PREFS_NAME, Context.MODE_PRIVATE
    )
    private val gson = Gson()

    fun save(accountId: String, site: GhostSite) {
        val json = gson.toJson(site)
        prefs.edit().putString(keyForAccount(accountId), json).apply()
    }

    fun get(accountId: String): GhostSite? {
        val json = prefs.getString(keyForAccount(accountId), null) ?: return null
        return try {
            gson.fromJson(json, GhostSite::class.java)
        } catch (e: Exception) {
            null
        }
    }

    fun getVersion(accountId: String): String? {
        return get(accountId)?.version
    }

    fun remove(accountId: String) {
        prefs.edit().remove(keyForAccount(accountId)).apply()
    }

    private fun keyForAccount(accountId: String): String = "site_$accountId"

    companion object {
        const val PREFS_NAME = "site_metadata_cache"
    }
}
