package cgmblelib.base;

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

import cgmblelib.utils.Tool;


public class BSharedPreferences {
  private static BSharedPreferences mInstance;

  private SharedPreferences mSharedPreferences;
  private SharedPreferences.Editor mEditor;


  private BSharedPreferences(Context context) {
    mSharedPreferences = context.getSharedPreferences(Tool.getAppPackageName(context), Context.MODE_PRIVATE);
    mEditor = mSharedPreferences.edit();
  }

  public static void init(Context context) {
    mInstance = new BSharedPreferences(context);
  }

  public static synchronized BSharedPreferences getInstance(Context context) {
    if (mInstance == null) {
      mInstance = new BSharedPreferences(context.getApplicationContext());
    }
    return mInstance;
  }

  public boolean saveData(String key, Object value) {
    if (value instanceof Integer)
      mEditor.putInt(key, (Integer) value);
    else if (value instanceof String)
      mEditor.putString(key, String.valueOf(value));
    else if (value instanceof Boolean)
      mEditor.putBoolean(key, (Boolean) value);
    else if (value instanceof Float)
      mEditor.putFloat(key, (Float) value);
    else if (value instanceof Long)
      mEditor.putLong(key, (Long) value);
    else
      mEditor.putString(key, String.valueOf(value));
    return mEditor.commit();
  }

  public String getData(String key) {
    if (sharedContains(key)) {
      return mSharedPreferences.getString(key, "");
    }
    return null;
  }

  public int getDataInt(String key) {
    if (sharedContains(key)) {
      return mSharedPreferences.getInt(key, -1);
    }
    return 0;
  }


  public int getDataInt(String key, int defalut) {
    if (sharedContains(key)) {
      return mSharedPreferences.getInt(key, defalut);
    }
    return defalut;
  }

  public boolean getDataBoolean(String key) {
    return getDataBoolean(key, false);
  }

  public boolean getDataBoolean(String key, boolean defaultBoolean) {
    if (sharedContains(key)) {
      return mSharedPreferences.getBoolean(key, defaultBoolean);
    }
    return defaultBoolean;
  }

  public float getDataFloat(String key) {
    if (sharedContains(key)) {
      return mSharedPreferences.getFloat(key, 0);
    }
    return 0;
  }

  public long getDataLong(String key) {
    if (sharedContains(key)) {
      return mSharedPreferences.getLong(key, 0);
    }
    return 0;
  }

  public void removeData(String key) {
    if (sharedContains(key)) {
      mEditor.remove(key);
    }
  }

  public void removeAll() {
    mEditor.clear();
    mEditor.commit();
  }

  private boolean sharedContains(String key) {
    return mSharedPreferences.contains(key);
  }

}
