package ${basePackage}.action.ajax.system;

import org.springframework.beans.factory.annotation.Autowired;
import ${basePackage}.frame.base.ErrorType;
import ${basePackage}.frame.schedule.Scheduler;
import ${basePackage}.frame.utils.StringUtil;
import ${basePackage}.module.system.ent.Schedule;
import ${basePackage}.module.system.req.ScheduleFindRequest;
import ${basePackage}.module.system.req.ScheduleStartRequest;
import ${basePackage}.module.system.req.ScheduleStopRequest;
import ${basePackage}.module.system.rsp.ScheduleFindResponse;
import ${basePackage}.module.system.rsp.ScheduleStartResponse;
import ${basePackage}.module.system.rsp.ScheduleStopResponse;

import java.util.Iterator;
import java.util.List;


public class ScheduleAjax {

    @Autowired
    private Scheduler scheduler;

    public ScheduleStartResponse start(ScheduleStartRequest request) {
        ScheduleStartResponse response = new ScheduleStartResponse();
        if (!scheduler.start(request.getId())) {
            response.addError(ErrorType.BUSINESS_ERROR, "启动失败!");
        }
        return response;
    }

    public ScheduleStopResponse stop(ScheduleStopRequest request) {
        ScheduleStopResponse response = new ScheduleStopResponse();
        if (!scheduler.stop(request.getId())) {
            response.addError(ErrorType.BUSINESS_ERROR, "停止失败!");
        }
        return response;
    }

    public ScheduleFindResponse find(ScheduleFindRequest request) {
        ScheduleFindResponse response = new ScheduleFindResponse();
        List<Schedule> schedules = scheduler.taskList();
        Iterator<Schedule> iterator = schedules.iterator();
        while (iterator.hasNext()) {
            Schedule next = iterator.next();
            if (!StringUtil.isEmpty(request.getTaskId()) && !next.getId().contains(request.getTaskId())) {
                iterator.remove();
            }
            if (!StringUtil.isEmpty(request.getTaskName()) && !next.getName().contains(request.getTaskName())) {
                iterator.remove();
            }
            if (request.getRun() != null && next.isRun() != request.getRun()) {
                iterator.remove();
            }
        }
        response.setResult(schedules);
        return response;
    }
}
