package com.css.simulation.resource.scheduler.infra.scheduler;

import api.common.pojo.constants.DictConstants;
import api.common.util.CollectionUtil;
import com.css.simulation.resource.scheduler.adapter.entity.ProjectStartMessageEntity;
import com.css.simulation.resource.scheduler.app.entity.ProjectWaitQueueEntity;
import com.css.simulation.resource.scheduler.app.service.ProjectApplicationService;
import com.css.simulation.resource.scheduler.domain.service.ProjectDomainService;
import com.css.simulation.resource.scheduler.infra.entity.ProjectEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class ProjectScheduler {
    @Resource
    private ProjectApplicationService projectApplicationService;
    @Resource
    private ProjectDomainService projectDomainService;

    /**
     * 调度项目启动
     */
    @Scheduled(fixedDelay = 1000)
    public void dispatchProject() {
        List<ProjectWaitQueueEntity> projectWaitQueue = projectDomainService.getWaitQueue();
        if (CollectionUtil.isNotEmpty(projectWaitQueue)) {
            ProjectWaitQueueEntity projectWaitQueueEntity = projectWaitQueue.get(0);
            String waitingType = projectWaitQueueEntity.getWaitingType();
            if (DictConstants.PROJECT_WAIT_TYPE_EXECUTE.equals(waitingType)) {
                log.debug("尝试启动等待中的项目：{}", projectWaitQueueEntity);
                projectApplicationService.checkIfCanRun(projectWaitQueueEntity);
            } else if (DictConstants.PROJECT_WAIT_TYPE_EXPAND.equals(waitingType)) {
                log.debug("尝试扩充运行中的项目：{}", projectWaitQueueEntity);
                ProjectStartMessageEntity projectStartMessageEntity = projectWaitQueueEntity.getProjectStartMessageEntity();
                String projectId = projectStartMessageEntity.getProjectId();
                ProjectEntity project = projectDomainService.getProjectByProjectId(projectId);
                if (DictConstants.PROJECT_COMPLETED.equals(project.getNowRunState())) {
                    log.info("等待扩充的项目" + projectWaitQueueEntity + "已运行完成，无需扩充。");
                    projectWaitQueue.remove(0);
                    projectDomainService.setWaitQueue(projectWaitQueue);
                    return;
                }
                projectApplicationService.checkIfCanRun(projectWaitQueueEntity);
            }
        }
    }

}
