package com.example.myapplication.util;

import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;

import java.util.HashSet;
import java.util.Set;

public class SharedPreferencesHelper
{
    private Context mContext;
    private SharedPreferences mSharedPref;
    public SharedPreferencesHelper(@NonNull Context context)
    {
        this.mContext = context;
        this.mSharedPref = PreferenceManager.getDefaultSharedPreferences(this.mContext);
    }

    public void savePref(@NonNull String key, @NonNull Object value)
    {
        SharedPreferences.Editor editor = this.mSharedPref.edit();
        if (value instanceof Boolean)
        {
            editor.putBoolean(key, (Boolean) value);
        }
        else if(value instanceof String)
        {
            editor.putString(key, (String) value);
        }
        else if (value instanceof Float)
        {
            editor.putFloat(key, (Float) value);
        }
        else if (value instanceof Integer)
        {
            editor.putInt(key, (Integer) value);
        }
        else  if (value instanceof Long)
        {
            editor.putLong(key, (Long) value);
        }
        else if (value instanceof Set)
        {
            Set set = (Set) value;
            Set<String> newSet = new HashSet<>();
            for (Object object : set)
            {
                newSet.add((String)object);
            }
            editor.putStringSet(key, newSet);
        }
        editor.apply();
    }

    public Object getPref(String key, Object defaultValue)
    {
        if (defaultValue instanceof String)
        {
            return this.mSharedPref.getString(key, (String) defaultValue);
        }
        else if (defaultValue instanceof Boolean)
        {
            return this.mSharedPref.getBoolean(key, (Boolean) defaultValue);
        }
        else if (defaultValue instanceof Float)
        {
            return this.mSharedPref.getFloat(key, (Float) defaultValue);
        }
        else if (defaultValue instanceof Integer)
        {
            return this.mSharedPref.getInt(key, (Integer) defaultValue);
        }
        else if (defaultValue instanceof Long)
        {
            return this.mSharedPref.getLong(key, (Long) defaultValue);
        }
        else if (defaultValue instanceof Set)
        {
            //noinspection unchecked
            return this.mSharedPref.getStringSet(key, (Set<String>) defaultValue);
        }
        else
        {
            return null;
        }
    }
}
