package org.security.xyun.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.security.config.XYunProperties;
import org.springblade.core.tool.utils.StringUtil;

import java.util.Arrays;

public class XYunPubUtil {
	public static JSONObject generateFrom(XYunProperties xYunProperties) {
		String eid = xYunProperties.getEId();
		String pubId = xYunProperties.getPubId();
		String pubSecret = xYunProperties.getPubSecret();
		String nonce = StringUtil.randomUUID();
		String time = String.valueOf(System.currentTimeMillis());
		JSONObject jsonFrom = new JSONObject();
		jsonFrom.put("no", eid);
		jsonFrom.put("pub", pubId);
		jsonFrom.put("nonce", nonce);
		jsonFrom.put("time", time);
		String pubToken = sha(eid, pubId, pubSecret, nonce, time);
		jsonFrom.put("pubtoken", pubToken);
		return jsonFrom;
	}

	private static String sha(String... data) {
		Arrays.sort(data);
		String join = StringUtils.join(data);
		String pubToken = DigestUtils.sha1Hex(join);
		return pubToken;
	}
}
