package com.lemenzo.messenger.mms;

import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.SubscriptionManager;
import java.util.HashSet;
import java.util.Set;

/** Durable metadata for an MMS NotificationInd until its RetrieveConf is persisted. */
public final class MmsDownloadStore {
    private static final String PREFS = "lemenzo_mms_downloads";
    private static final String TOKENS = "tokens";
    private final SharedPreferences prefs;

    public static final class Entry {
        public String token;
        public String location;
        public int subscriptionId;
        public boolean failed;
    }

    public MmsDownloadStore(Context context) {
        prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
    }

    public synchronized void put(String token, String location, int subscriptionId) {
        Set<String> tokens = new HashSet<>(prefs.getStringSet(TOKENS, new HashSet<>()));
        tokens.add(token);
        prefs.edit().putStringSet(TOKENS, tokens)
                .putString(token + ".location", location)
                .putInt(token + ".subscription", subscriptionId)
                .putBoolean(token + ".failed", false).commit();
    }

    public synchronized void markFailed(String token) {
        if (get(token) != null) prefs.edit().putBoolean(token + ".failed", true).commit();
    }

    public synchronized Entry get(String token) {
        Set<String> tokens = prefs.getStringSet(TOKENS, new HashSet<>());
        if (token == null || !tokens.contains(token)) return null;
        Entry e = new Entry();
        e.token = token;
        e.location = prefs.getString(token + ".location", null);
        e.subscriptionId = prefs.getInt(token + ".subscription",
                SubscriptionManager.INVALID_SUBSCRIPTION_ID);
        e.failed = prefs.getBoolean(token + ".failed", false);
        return e;
    }

    public synchronized void remove(String token) {
        Set<String> tokens = new HashSet<>(prefs.getStringSet(TOKENS, new HashSet<>()));
        tokens.remove(token);
        prefs.edit().putStringSet(TOKENS, tokens)
                .remove(token + ".location").remove(token + ".subscription")
                .remove(token + ".failed").commit();
    }
}
