package com.cm.security;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.cm.security.utils.AddressUtil;
import com.cm.security.utils.AesUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

public class License {

    private static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 获取license
     *
     * @param startTime
     * @param timeLong
     * @param mac
     * @param token
     * @return
     */
    public static String getLicense(String startTime, String timeLong, String mac, String token) {
        String result = null;
        if (null == startTime || startTime.isEmpty()) {
            return result;
        }
        if (null == timeLong || timeLong.isEmpty()) {
            return result;
        }
        if (null == mac || mac.isEmpty()) {
            return result;
        }
        if (null == token || token.isEmpty()) {
            return result;
        }
        try {
            // 开始时间
            String startTimeMD5 = DigestUtils.md5Hex(startTime);
            // MAC地址
            String macMD5 = DigestUtils.md5Hex(mac);
            // 使用时长
            String timeMD5 = DigestUtils.md5Hex(timeLong);
            // 构建license数组
            List<String> licenses = new ArrayList<String>();
            licenses.add(startTimeMD5);
            licenses.add(macMD5);
            licenses.add(timeMD5);
            // 构建可解密内容
            StringBuilder licenseFullPart = new StringBuilder();
            licenseFullPart.append(startTime).append(",");
            licenseFullPart.append(mac).append(",");
            licenseFullPart.append(timeLong).append(",").append("0");
            // license
            String licenseFull = new String(Base64.encodeBase64(AesUtil.aesCommonEncoder(token, licenseFullPart.toString()).getBytes("UTF-8")));
            licenses.add(licenseFull);
            StringBuilder license = new StringBuilder();
            for (String str : licenses) {
                if (license.length() > 0) {
                    license.append("-");
                }
                license.append(str);
            }
            result = new String(Base64.encodeBase64((license.toString().getBytes("UTF-8"))), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    /**
     * 校验license
     *
     * @param token
     * @param license
     * @return
     */
    public static boolean checkLicense(String token, String license) {
        if (null == token || token.isEmpty()) {
            return false;
        }
        if (null == license || license.isEmpty()) {
            return false;
        }
        try {
            byte[] licenseByte = Base64.decodeBase64(license);
            String licenseFull = new String(licenseByte, "UTF-8");
            String[] checkInfos = licenseFull.split("-");
            String startTime = checkInfos[0];
            String mac = checkInfos[1];
            String time = checkInfos[2];
            String fullInfo = checkInfos[3];
            String info = new String(Base64.decodeBase64(fullInfo), "UTF-8");
            String[] checkInfo = AesUtil.aesCommonDecoder(token, info).split(",");
            // 校验时间
            if (!startTime.equals(DigestUtils.md5Hex(checkInfo[0]))) {
                return false;
            }
            // 开始时间大于当前时间
            if (SDF.parse(checkInfo[0]).getTime() > System.currentTimeMillis()) {
                return false;
            }
            // mac，mac不匹配
            List<String> macIds = AddressUtil.getMacIds();
            boolean confirmMac = false;
            for (String macId : macIds) {
                if (checkInfo[1].equals(macId) && mac.equals(DigestUtils.md5Hex(checkInfo[1]))) {
                    confirmMac = true;
                    break;
                }
            }
            if (!confirmMac) {
                return false;
            }
            // 授权时长
            if (!time.equals(DigestUtils.md5Hex(checkInfo[2]))) {
                return false;
            }
            // 当前有效时间
            if (Integer.parseInt(checkInfo[2]) < Integer.parseInt(checkInfo[3])) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 更新license
     *
     * @param token
     * @param license
     * @return
     */
    public static String updateLicense(String token, String license) {
        String result = null;
        if (null == license || license.isEmpty()) {
            return result;
        }
        try {
            byte[] licenseByte = Base64.decodeBase64(license);
            String licenseFull = new String(licenseByte, "UTF-8");
            String[] checkInfos = licenseFull.split("-");
            String startTime = checkInfos[0];
            String mac = checkInfos[1];
            String time = checkInfos[2];
            String fullInfo = checkInfos[3];
            String[] checkInfo = AesUtil
                    .aesCommonDecoder(token,
                            new String(Base64.decodeBase64(fullInfo), "UTF-8"))
                    .split(",");
            checkInfo[3] = String.valueOf(Integer.parseInt(checkInfo[3]) + 1);
            StringBuilder newCheckInfo = new StringBuilder();
            for (String newCheck : checkInfo) {
                if (newCheckInfo.length() > 0) {
                    newCheckInfo.append(",");
                }
                newCheckInfo.append(newCheck);
            }
            licenseFull = new String(Base64.encodeBase64(AesUtil.aesCommonEncoder(token, newCheckInfo.toString()).getBytes("UTF-8")), "UTF-8");
            result = new String(Base64.encodeBase64(new StringBuilder(startTime).append("-").append(mac).append("-")
                    .append(time).append("-").append(licenseFull).toString().getBytes()), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

}
