package com.yuji.ec.utility;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;

public class PrefUtilImpl implements PrefUtil {
	private static final String EVER_CLIP_ACTIVITY = "EverClipActivity";
	private static final String PACKAGE_COM_YUJI_EC = "com.yuji.ec";
	private Context context;

	public PrefUtilImpl(Context context) {
		this.context = context;
	}

	public void put(String key, String value) {
		synchronized (this) {
			SharedPreferences pref = null;
			try {
				Context ctxt = context.createPackageContext(PACKAGE_COM_YUJI_EC,
						Context.CONTEXT_RESTRICTED);
				pref = ctxt.getSharedPreferences(EVER_CLIP_ACTIVITY,
						Context.MODE_PRIVATE);
			} catch (NameNotFoundException e) {
				Debug.d(this, null, e);
				return;
			}

			Editor e = pref.edit();
			e.putString(key, value);
			e.commit();
		}
	}

	public void put(String key, int value) {
		put(key, String.valueOf(value));
	}

	public void put(String key, long value) {
		put(key, String.valueOf(value));
	}

	public String get(String key) {
		String val;
		
		synchronized (this) {
			SharedPreferences pref = null;
			try {
				Context ctxt = context.createPackageContext(PACKAGE_COM_YUJI_EC,
						Context.CONTEXT_RESTRICTED);
				pref = ctxt.getSharedPreferences(EVER_CLIP_ACTIVITY,
						Context.MODE_WORLD_READABLE);
			} catch (NameNotFoundException e) {
				Debug.d(this, null, e);
				return null;
			}
			val = pref.getString(key, null);
		}

		return val;
	}

	public int getInt(String key) {
		return Integer.parseInt(get(key));
	}

	public long getLong(String key) {
		return Long.parseLong(get(key));
	}

	public String get(String key, String initValue) {
		String value = get(key);
		if (value != null) {
			return value;
		}
		put(key, initValue);
		return initValue;
	}

	public int getInt(String key, int initValue) {
		return Integer.valueOf(get(key, String.valueOf(initValue)));
	}

	public long getLong(String key, long initValue) {
		return Long.valueOf(get(key, String.valueOf(initValue)));
	}
	
	public void copy(String srcKey, String dstKey){
		String value = get(srcKey);
		put(dstKey, value);
	}
	
	public void remove(String key) {
		put(key, null);
	}
}
