package com.rrtx.services.common.hostenv;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import com.min.sha1.SHA1;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.min.base64.Base64;

import sun.misc.BASE64Encoder;

/**
 * 
 * 对传输字段MAC加密
 * 
 * @author zhangzz
 */
public class MacUtils {
    private static final char hexDigits[] = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};

public static String handleMac(String content) {
    JSONObject root = null;
    try {
        root = new JSONObject(content);
    } catch (JSONException e1) {
    }
    String str = "";

    List<String> jsonList = new ArrayList<String>();
    addHash(root, jsonList);
    Collections.sort(jsonList);
    for (int i = 0; i < jsonList.size(); i++) {
        str += jsonList.get(i);
    }

    try {
    	String mac = new BASE64Encoder().encode(encode16(
                new SHA1().getDigestOfString(new BASE64Encoder().encode(str.getBytes())
                        .getBytes())).getBytes());
        root.put("mac", mac);
    } catch (JSONException e) {
    }
    return root.toString();

}

public static JSONArray encryptParameter(JSONArray jsonArray) {
    JSONObject root = jsonArray.optJSONObject(0);
    String str = "";

    List<String> jsonList = new ArrayList<String>();
    addHash(root, jsonList);
    Collections.sort(jsonList);
    for (int i = 0; i < jsonList.size(); i++) {
        str += jsonList.get(i);
    }

    try {
        root.put("mac", new BASE64Encoder().encode(encode16(
                new SHA1().getDigestOfString(new BASE64Encoder().encode(str.getBytes())
                        .getBytes())).getBytes()));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonArray;
}

public static String encode16(byte[] tmp) {
    char str[] = new char[16 * 2];
    int k = 0;
    for (int i = 0; i < 16; i++) {
        byte byte0 = tmp[i];
        str[k++] = hexDigits[byte0 >>> 4 & 0xf];
        str[k++] = hexDigits[byte0 & 0xf];
    }
    return new String(str);
}

private static void addHash(JSONObject objectSub, List<String> list) {
    Iterator<?> it = objectSub.keys();
    while (it.hasNext()) {
        String name = it.next().toString();
        try {
            addHash(objectSub.getJSONArray(name), name, list);
        } catch (JSONException e) {
            try {
                addHash(objectSub.getJSONObject(name), list);
            } catch (JSONException e1) {
            	Object value=objectSub.opt(name);
                if(value instanceof String){
                	if(!value.equals("")){
                		list.add(name + value);
                	}
                }else{
                	if(!String.valueOf(value).equals("null")&&!String.valueOf(value).equals("")){
                		list.add(name + value);
                	}
                }
            }

        }
    }

}

private static void addHash(JSONArray array, String name, List<String> list) {
    for (int i = 0; i < array.length(); i++) {
        try {
            JSONArray arraySub = array.getJSONArray(i);
            addHash(arraySub, name, list);
        } catch (JSONException e) {
            try {
                JSONObject object = array.getJSONObject(i);
                addHash(object, list);
            } catch (JSONException e1) {
//                String value = array.optString(i);
            	Object value=array.opt(i);
                if(value instanceof String){
                	if (!value.equals("")) {
                        list.add(name + value);
                    }
                }else{
                	if(!String.valueOf(value).equals("null")&&!String.valueOf(value).equals("")){
                		list.add(name + value);
                	}
                }
            }
        }
    }
}

/**
 * Method Name：createMac Description：生成mac
 * 
 * @param content Creator：muzhengjun Create DateTime：2013-10-22
 */
public static String createMac(String content) {
    JSONObject root = null;
    try {
        root = new JSONObject(content);
    } catch (JSONException e1) {
    }
    root.remove("mac");
    String str = "";

    List<String> jsonList = new ArrayList<String>();
    addHash(root, jsonList);
    Collections.sort(jsonList);
    for (int i = 0; i < jsonList.size(); i++) {
        str += jsonList.get(i);
    }

    String mac = null;
	try {
		mac = Base64.encode(encode16(
		                new SHA1().getDigestOfString(Base64.encode(str.getBytes("utf-8"))
		                        .getBytes("utf-8"))).getBytes("utf-8"));
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    return mac;
}

	/**
	 * 生成核心MAC
	 */
	public static String creatHostMac(String str) {
	    String mac = null;
		try {
			mac = Base64.encode(encode16(
			                new SHA1().getDigestOfString(Base64.encode(str.getBytes("utf-8"))
		                        .getBytes("utf-8"))).getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	    return mac;
	}

	public static void main(String arg[]) {
		String str = "appVerARD.2.0.0bkId101brandMI-ONE PlusdId94:db:c9:62:88:d2dTyp02isWifiYmoduleId02000000moduleId02000000moduleId02000000moduleId02000000moduleId03000000moduleId03000000moduleId03000000moduleId03000000moduleId03000000moduleId03000000moduleId03000000moduleId04000000moduleId04000000moduleId04000000moduleId04000000moduleId07000000moduleId07000000moduleId07000000moduleId07000000moduleId07000000moduleId07000000moduleId08000000moduleId08000000moduleId08000000moduleId08000000moduleId09000000moduleId09000000moduleId09000000moduleId10000000moduleId10000000moduleId10000000moduleId10000000moduleId11000000moduleId11000000moduleId11000000moduleId11000000moduleId12000000moduleId12000000moduleId12000000moduleId12000000moduleId12000000moduleId12000000moduleId999999moduleId999999opIdmoduleInfoosVerARD.4.1.2rqId01rspFmtJSONsn2015071421590074694:db:c9:62:88:d2stime20150714215900763subModuleId02010000subModuleId02020000subModuleId02030000subModuleId03010000subModuleId03020000subModuleId03030000subModuleId03040000subModuleId03050000subModuleId03060000subModuleId04010000subModuleId04020000subModuleId04030000subModuleId07010000subModuleId07020000subModuleId07030000subModuleId07040000subModuleId07050000subModuleId08010000subModuleId08020000subModuleId08030000subModuleId10000000subModuleId10000000subModuleId11010000subModuleId11020000subModuleId11030000subModuleId12010000subModuleId12020000subModuleId12030000subModuleId12040000subModuleId12050000subModuleId999999transId115050version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001version000000000000001";
	    String mac = null;
			mac = Base64.encode(encode16(
	                new SHA1().getDigestOfString(Base64.encode(str.getBytes())
	                        .getBytes())).getBytes());
		System.out.println(mac);
	}
}
