package com.swoosh.microblog.data

import android.content.Context
import android.content.SharedPreferences
import com.swoosh.microblog.data.model.PostFilter
import com.swoosh.microblog.data.model.SortOrder

/**
 * Persists the user's last-selected feed filter and sort order
 * using regular (non-encrypted) SharedPreferences since these
 * are not sensitive values.
 */
class FeedPreferences(context: Context) {

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

    var filter: PostFilter
        get() {
            val name = prefs.getString(KEY_FILTER, PostFilter.ALL.name)
            return try {
                PostFilter.valueOf(name!!)
            } catch (e: IllegalArgumentException) {
                PostFilter.ALL
            }
        }
        set(value) = prefs.edit().putString(KEY_FILTER, value.name).apply()

    var sortOrder: SortOrder
        get() {
            val name = prefs.getString(KEY_SORT_ORDER, SortOrder.NEWEST.name)
            return try {
                SortOrder.valueOf(name!!)
            } catch (e: IllegalArgumentException) {
                SortOrder.NEWEST
            }
        }
        set(value) = prefs.edit().putString(KEY_SORT_ORDER, value.name).apply()

    companion object {
        const val PREFS_NAME = "swoosh_feed_prefs"
        const val KEY_FILTER = "feed_filter"
        const val KEY_SORT_ORDER = "feed_sort_order"
    }
}
