package com.skr.mdm.api.license;

import com.skr.mdm.license.LicenseVerify;
import com.skr.mdm.license.LicenseVerifyParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * @author nfq
 * @date 2021/09/01 17:59
 */
@Component
@Slf4j
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${mdm.license.company}")
    private Boolean companyLicense;

    /**
     * 证书subject
     */
    @Value("${license.subject}")
    private String subject;
    /**
     * 公钥别称
     */
    @Value("${license.publicAlias}")
    private String publicAlias;
    /**
     * 访问公钥库的密码
     */
    @Value("${license.storePass}")
    private String storePass;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (companyLicense) {
            log.info("====================公司授权=================");
            return;
        }
        // springboot启动后安装证书
        ApplicationContext context = event.getApplicationContext().getParent();
        String licensePath = MdmLicenseVerify.getLicensePath();
        log.info("licensePath:{}", licensePath);
        if (context == null) {
            if (StringUtils.isNotBlank(licensePath)) {
                File file = new File(licensePath);
                if (!file.exists()) {
                    log.info("======================= 证书不存在 =============================");
                    return;
                }
                LicenseVerifyParam param = new LicenseVerifyParam();
                param.setSubject(subject);
                param.setPublicAlias(publicAlias);
                param.setStorePass(storePass);
                param.setLicensePath(licensePath);
                try {
                    param.setPublicKeysStorePath(MdmLicenseVerify.getLicensePublicCertPath());
                } catch (FileNotFoundException e) {
                    log.error("获取license公钥路径异常：{}", e);
                    throw new RuntimeException(e);
                }
                LicenseVerify licenseVerify = new LicenseVerify();
                licenseVerify.install(param);
            }
        }
    }
}