package com.fdkankan.modeling.job;

import com.fdkankan.common.util.RubberSheetingUtil;
import com.fdkankan.modeling.constants.SysConstants;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
public class EcsJob {

    private static final Logger log = LoggerFactory.getLogger(EcsJob.class);

    @Autowired
    private RubberSheetingUtil rubberSheetingUtil;

    @PostConstruct
    public void deleteEcs() {
        log.info("常驻服务列表：{}", SysConstants.residenceServiceHostName);
        log.info("当前服务名称：{}", SysConstants.hostName);
        log.info("当前服务是否是常驻服务：{}", SysConstants.residenceServiceHostName.contains(SysConstants.hostName));
        if (!ObjectUtils.isEmpty(SysConstants.residenceServiceHostName) && SysConstants.residenceServiceHostName.contains(SysConstants.hostName)) {
            log.info("此服务是常驻服务");
            return;
        }
        Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> {

                    // 判断是否有任务执行
                    if (SysConstants.SYSTEM_BUILDING) {
                        return;
                    }
                    log.info("服务未构建，准备停止服务！");
                    if (!SysConstants.executorService.isShutdown()) {
                        SysConstants.SYSTEM_OFFING = true;
                        if (!SysConstants.SYSTEM_BUILDING) {
                            SysConstants.executorService.shutdown();
                            log.error("{} 线程池关闭，不接受新的构建请求！", SysConstants.hostName);
                        }else{
                            SysConstants.SYSTEM_OFFING = false;
                            log.error("{} 服务构建中，退出停止服务请求！", SysConstants.hostName);
                        }
                    }
                    // 没有任务执行时，则退出
                    if (SysConstants.executorService.isShutdown() && SysConstants.executorService.isTerminated()) {
                        log.error("{} 请求阿里云关闭弹性伸缩", SysConstants.hostName);
                        rubberSheetingUtil.deleteEcs(SysConstants.hostName);
                    } else {
                        log.error("{} 服务构建中，退出删除程序失败！", SysConstants.hostName);
                    }
                },
                50, 60, TimeUnit.MINUTES);
    }
}
