package com.helpshift.react.storage;

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

import com.helpshift.util.JsonUtils;
import com.helpshift.util.Utils;

import java.util.HashMap;
import java.util.Map;

/**
 * This class stores the config values which are required when
 * the app is not in memory and we need to make install() call for notifications
 */
public class HelpshiftReactNativeStorage {
  private static HelpshiftReactNativeStorage storage;
  private final SharedPreferences sharedPreferences;

  public static final String DOMAIN_NAME = "domainName";
  public static final String PLATFORM_ID = "platformId";
  public static final String INSTALL_CONFIG = "installConfig";


  private HelpshiftReactNativeStorage(Context context) {
    this.sharedPreferences = context.getSharedPreferences("__helpshift_sdkx_reactnative_prefs",
                                                         Context.MODE_PRIVATE);
  }

  public static synchronized HelpshiftReactNativeStorage getInstance(Context context) {
    if (storage == null) {
      storage = new HelpshiftReactNativeStorage(context);
    }
    return storage;
  }

  public void put(String key, String value) {

    if (Utils.isEmpty(key)) {
      return;
    }

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
  }

  public String getString(String key) {
    if (Utils.isEmpty(key)) {
      return "";
    }
    return sharedPreferences.getString(key, "");
  }

  public void putJsonStringOfMap(String key, String jsonStringOfMap) {

    if (Utils.isEmpty(key)) {
      return;
    }

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, jsonStringOfMap);
    editor.commit();
  }

  public Map<String, Object> getMap(String key) {
    if (Utils.isEmpty(key)) {
      return new HashMap<>();
    }
    String jsonStringOfMap = sharedPreferences.getString(key, "");
    if (Utils.isEmpty(jsonStringOfMap)) {
      return new HashMap<>();
    }
    return new HashMap<>(JsonUtils.jsonStringToMap(jsonStringOfMap));
  }
}
