package com.usky.rule.jobs;

import com.usky.rule.enums.TriggerTypeEnum;
import com.usky.rule.vo.action.RuleEngineAction;
import com.usky.rule.vo.log.RuleEngineDetailLog;
import com.usky.rule.listeners.CommonListener;
import com.usky.rule.util.RuleEngineUtil;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.quartz.CronTrigger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;

@DisallowConcurrentExecution
@Slf4j
public class CommonJob implements Job {
    @Resource
    private RuleEngineUtil ruleEngineUtil;

    public CommonJob() {
    }

    public void execute(JobExecutionContext context) {
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        Long ruleEngineId = (Long)dataMap.get("ruleEngineId");
        Long projectId = (Long)dataMap.get("projectId");
        Long spaceId = (Long)dataMap.get("spaceId");
        List<RuleEngineAction> actions = (List)dataMap.get("actions");
        RuleEngineDetailLog detail = (RuleEngineDetailLog)context.get("detail");
        if (detail == null) {
            detail = CommonListener.initRuleEngineDetailLog((CronTrigger)context.getTrigger(), LocalDateTime.now());
            detail.setConstraints(new ArrayList());
        }
        log.info("commonJob start ruleEngineId: {}, detail: {}, spaceId: {}", ruleEngineId, detail, spaceId);

        this.ruleEngineUtil.performMultipleDevicesControl(ruleEngineId, true, TriggerTypeEnum.CRON.getType(), projectId, spaceId, actions, detail);
    }
}
