package de.beyondsoft.ownchat.data.prefs;

import com.securepreferences.SecurePreferences;

import android.content.SharedPreferences;

import java.util.Map;

/**
 * Created by imarneanu on 2/10/17.
 */
abstract class BasePreference<T> {

    final SharedPreferences mPreferences;
    final String mKey;
    final T mDefaultValue;

    BasePreference(SharedPreferences preferences, String key, T defaultValue) {
        mPreferences = preferences;
        mKey = key;
        mDefaultValue = defaultValue;
    }

    BasePreference(SecurePreferences preferences, String key, T defaultValue) {
        mPreferences = preferences;
        mKey = key;
        mDefaultValue = defaultValue;
    }

    public boolean isSet() {
        return mPreferences.contains(mKey);
    }

    public void delete() {
        mPreferences.edit().remove(mKey).apply();
    }

    /**
     * Method needs to be called when {@link SecurePreferences} are used.
     */
    public void deleteFromSecurePreference() {
        String secureKey = SecurePreferences.hashPrefKey(mKey);
        for (Map.Entry<String, ?> entry : ((SecurePreferences) mPreferences).getAll().entrySet()) {
            final String key = entry.getKey();
            //noinspection ConstantConditions
            if (key.equals(secureKey)) {
                mPreferences.edit().remove(mKey).apply();
                return;
            }
        }
    }

    public abstract T get();

    public abstract void set(T value);

}
