package com.backfire.doudizhu.common;

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

import com.backfire.doudizhu.userinfo.UserMessageCenter;

public class MyJson {
	private Map<String, Object> content;

	public MyJson() {
		content = new HashMap<String, Object>();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public MyJson(Map content) {
		this.content = content;
		content.put("platFormID", UserMessageCenter.getInstance().getPlatFormID());
		content.put("ver", UserMessageCenter.getInstance().version);
		content.put("paytype", UserMessageCenter.payType);
	}

	public void put(String key, Object value) {
		content.put(key, value);
	}

	@SuppressWarnings("rawtypes")
	public String toString() {
		if (this.content.isEmpty()) {
			return "{}";
		}
		String result = "{";
		Set<String> keys = content.keySet();
		for (String key : keys) {
			Object value = content.get(key);
			if(value!=null){	
				String valueString = value.toString();
				result += "\"" + unicode(key) + "\":";
				if (value instanceof MyJson) {
					result += valueString;
				} else if (value instanceof Map) {
					result += (new MyJson((Map) value).toString());
				} else if (value instanceof byte[]) {
					result += "\"\"";
				} else{
					result += "\"" + unicode(valueString) + "\"";
				}
				result += ",";
			}
		}
		result = result.substring(0, result.length() - 1);
		result += "}";

		return result;
	}

	private String unicode(String org) {
		if (org == null || org.length() == 0) return "";

		StringBuffer sb = new StringBuffer();
		for (char ch : org.toCharArray()) {
			switch(ch) {
				case '"':
					sb.append("\\\"");
					break;
				case '\\':
	                sb.append("\\\\");
	                break;
	            case '\b':
	                sb.append("\\b");
	                break;
	            case '\f':
	                sb.append("\\f");
	                break;
	            case '\n':
	                sb.append("\\n");
	                break;
	            case '\r':
	                sb.append("\\r");
	                break;
	            case '\t':
	                sb.append("\\t");
	                break;
	            case '/':
	                sb.append("\\/");
	                break;
	            default:
	            	if (ch >= '\u0000' && ch <= '\u001F') {
	                    String ss = Integer.toHexString(ch);
	                    sb.append("\\u");
	                    for (int k = 0; k < 4 - ss.length(); k++) {
	                        sb.append('0');
	                    }
	                    sb.append(ss.toUpperCase());
	                } else {
	                    sb.append(ch);
	                }
			}
		}
		return sb.toString();
	}
}

