package com.mobify.astro;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;

import com.mobify.astro.messaging.EventRegistrar;
import com.mobify.astro.messaging.MessageSender;
import com.mobify.astro.messaging.RpcMessageListener;
import com.mobify.astro.messaging.annotations.RpcMethod;


public class SettingsStore extends RpcMessageListener {

    protected static final String ADDRESS = "AstroSettingsStore:0";
    private final static String TAG = SettingsStore.class.getName();
    private final static String SETTINGS_STORE_FILE_KEY = "com.mobify.astro.SETTINGS_STORAGE";

    final static String KEY_ERROR = "Key cannot be null or empty string.";
    final static String VALUE_ERROR = "Value cannot be null.";

    private SharedPreferences sharedPref;
    private SharedPreferences.Editor editor;

    public class SettingsStoreException extends AstroException {
        public SettingsStoreException(String message) {
            super(TAG + ": " + message);
        }
    }

    public SettingsStore(@NonNull Context context, @NonNull EventRegistrar eventRegistrar, @NonNull MessageSender messageSender) {
        super(eventRegistrar, messageSender);

        sharedPref = context.getSharedPreferences(SETTINGS_STORE_FILE_KEY, Context.MODE_PRIVATE);
        editor = sharedPref.edit();
    }

    @Override
    public String getInstanceAddress() {
        return ADDRESS;
    }

    @RpcMethod(methodName = "set", parameterNames = {"key", "value"})
    public void set(String key, String value) throws Exception {
        if (key == null || key.isEmpty() || value == null) {
            throw new SettingsStoreException(KEY_ERROR + " " + VALUE_ERROR);
        }

        editor.putString(key, value).apply();
    }

    @RpcMethod(methodName = "get", parameterNames = {"key"})
    public String get(String key) throws Exception {
        if (key == null || key.isEmpty()) {
            throw new SettingsStoreException(KEY_ERROR);
        }

        return sharedPref.getString(key, null);
    }

    @RpcMethod(methodName = "delete", parameterNames = {"key"})
    public void delete(String key) throws Exception {
        if (key == null || key.isEmpty()) {
            throw new SettingsStoreException(KEY_ERROR);
        }

        editor.remove(key).apply();
    }
}
