package cn.security.license.core;

import de.schlichtherle.license.LicenseContent;
import de.schlichtherle.license.LicenseContentException;
import de.schlichtherle.license.LicenseManager;
import de.schlichtherle.license.LicenseNotary;
import de.schlichtherle.license.LicenseParam;
import de.schlichtherle.license.NoLicenseInstalledException;
import de.schlichtherle.xml.GenericCertificate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cn.security.license.core.abs.AbstractServerInfos;
import cn.security.license.util.RegexUtil;
import cn.util.core.LogKit;

import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * 自定义LicenseManager，用于增加额外的服务器硬件信息校验
 */
public class LicenseCustomManager extends LicenseManager
{
    private static Logger logger = LogManager.getLogger(LicenseCustomManager.class);

    private static volatile LicenseCheckModel SERVER_INFOS = null;
    //XML编码
    private static final String XML_CHARSET = "UTF-8";
    //默认BUFSIZE
    private static final int DEFAULT_BUFSIZE = 8 * 1024;

    public LicenseCustomManager() {

    }

    public LicenseCustomManager(LicenseParam param) {
        super(param);
    }

    /**
     * 复写create方法
     */
    @Override
    protected synchronized byte[] create(
    		LicenseContent content, 
    		LicenseNotary notary)  
    				throws Exception {
        initialize(content);
        this.validateCreate(content);
        final GenericCertificate certificate = notary.sign(content);
        return getPrivacyGuard().cert2key(certificate);
    }

    /**
     * 复写install方法，其中validate方法调用本类中的validate方法，校验IP地址、Mac地址等其他信息
      */
    @Override
    protected synchronized LicenseContent install(final byte[] key, final LicenseNotary notary)  throws Exception {
        final GenericCertificate certificate = getPrivacyGuard().key2cert(key);
        notary.verify(certificate);
        final LicenseContent content = (LicenseContent)this.load(certificate.getEncoded());
        /** 加入自己额外的许可内容信息认证  */
        this.validate(content);
        setLicenseKey(key);
        setCertificate(certificate);
        return content;
    }

    /**
     * 复写verify方法，调用本类中的validate方法，校验IP地址、Mac地址等其他信息
     */
    @Override
    protected synchronized LicenseContent verify(final LicenseNotary notary)
            throws Exception {
        GenericCertificate certificate = getCertificate();

        // Load license key from preferences,
        final byte[] key = getLicenseKey();
        if (null == key){
            throw new NoLicenseInstalledException(getLicenseParam().getSubject());
        }

        certificate = getPrivacyGuard().key2cert(key);
        notary.verify(certificate);
        final LicenseContent content = (LicenseContent)this.load(certificate.getEncoded());
        /** 增加额外的自己的license校验方法，校验ip、mac、cpu序列号等 */
        this.validate(content);
        setCertificate(certificate);

        return content;
    }

    /**
     * 校验生成证书的参数信息
     * @param content 证书正文
     */
    protected synchronized void validateCreate(final LicenseContent content)  throws LicenseContentException {
        final Date now = new Date();
        final Date notBefore = content.getNotBefore();
        final Date notAfter = content.getNotAfter();
        if (null != notAfter && now.after(notAfter)){
            String message = "证书失效时间不能早于当前时间";
            LogKit.error(message);
            throw new LicenseContentException(message);
        }
        if (null != notBefore && null != notAfter && notAfter.before(notBefore)){
            String message = "证书生效时间不能晚于证书失效时间";
            LogKit.error(message);
            throw new LicenseContentException(message);
        }
        final String consumerType = content.getConsumerType();
        if (null == consumerType){
            String message = "用户类型不能为空";
            LogKit.error(message);
            throw new LicenseContentException(message);
        }
    }


    /**
     * 复写validate方法，增加IP地址、Mac地址等其他信息校验
     * @param content LicenseContent
     */
    @Override
    protected synchronized void validate(final LicenseContent content)
            throws LicenseContentException {
        //1. 首先调用父类的validate方法
        super.validate(content);
        //2. 然后校验自定义的License参数
        //License中可被允许的参数信息
        LicenseCheckModel expectedCheckModel = (LicenseCheckModel) content.getExtra();
        //当前服务器真实的参数信息
        LicenseCheckModel serverCheckModel = getServerInfos();
        if(expectedCheckModel != null && serverCheckModel != null)
        {
           //校验IP地址
            if(!RegexUtil.checkWildcard(expectedCheckModel.getIpAddress(),serverCheckModel.getIpAddress())){
                throw new LicenseContentException("当前服务器的IP没在授权范围内");
            }
            
            //校验Mac地址
            if(!RegexUtil.check(expectedCheckModel.getMacAddress(),serverCheckModel.getMacAddress())){
                throw new LicenseContentException("当前服务器的Mac地址没在授权范围内");
            }
            
            //校验主板序列号
            if(!RegexUtil.check(expectedCheckModel.getMainBoardSerial(),serverCheckModel.getMainBoardSerial())){
                throw new LicenseContentException("当前服务器的主板序列号没在授权范围内");
            }
            
            //校验CPU序列号
            if(!RegexUtil.check(expectedCheckModel.getCpuSerial(),serverCheckModel.getCpuSerial())){
                throw new LicenseContentException("当前服务器的CPU序列号没在授权范围内");
            }
        }else{
            throw new LicenseContentException("不能获取服务器硬件信息");
        }
    }

    /**
     * 获取LicenseContent
     *
     * @return
     * @throws Exception
     */
    public LicenseContent getContent() throws Exception {
        GenericCertificate certificate = getCertificate();

        // Load license key from preferences,
        final byte[] key = getLicenseKey();
        if (null == key) {
            throw new NoLicenseInstalledException(getLicenseParam().getSubject());
        }

        certificate = getPrivacyGuard().key2cert(key);
        final LicenseContent content = (LicenseContent) this.load(certificate.getEncoded());
        return content;
    }

    /**
     * 重写XMLDecoder解析XML
     * @param encoded XML类型字符串
     * @return java.lang.Object
     */
    private Object load(String encoded){
        BufferedInputStream inputStream = null;
        XMLDecoder decoder = null;
        try {
            inputStream = new BufferedInputStream(new ByteArrayInputStream(encoded.getBytes(XML_CHARSET)));

            decoder = new XMLDecoder(new BufferedInputStream(inputStream, DEFAULT_BUFSIZE),null,null);

            return decoder.readObject();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            try {
                if(decoder != null){
                    decoder.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (Exception e) {
                logger.error("XMLDecoder解析XML失败",e);
            }
        }
        return null;
    }

    /**
     * 获取当前服务器需要额外校验的License参数
     *
     * @return LicenseCheckModel
     */
    private LicenseCheckModel getServerInfos() {
        if(SERVER_INFOS == null){
            synchronized (LicenseCustomManager.class){
                if(SERVER_INFOS == null){
                    SERVER_INFOS = new LicenseCheckModel();
                    SERVER_INFOS.copyTo();
                }
            }
        }
        return SERVER_INFOS;
    }
    
    /**
     * 获取当前服务器需要额外校验的License参数
     */
    public LicenseCheckModel getServerInfos_old(){
        //操作系统类型
        String osName = System.getProperty("os.name").toLowerCase();
        AbstractServerInfos abstractServerInfos = null;

        //根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        }else{//其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }
        return abstractServerInfos.getServerInfos();
    }
}
