/**
 * 
 */
package org.springblade.etl.task.service;

import java.util.Optional;
import java.util.ServiceLoader;

import org.springblade.etl.task.model.DaemonTaskConfig;
import org.springblade.etl.task.model.DaemonTaskType;

/**
 * @author wookvn
 *
 */
public interface DaemonTask {
	
	/**
	 * 运行任务
	 */
	public void deal();
	
	/**
	 * 
	 * @param config
	 * @return
	 */
	public DaemonTask setConfig(DaemonTaskConfig config);
	
	/**
	 * 类型
	 * @return
	 */
	public DaemonTaskType getType();
	
	/**
	 * 是否支持
	 * @param type
	 * @return
	 */
	default boolean supports(DaemonTaskType type) {
		return type == getType();
	}
	
	static DaemonTask ofService(DaemonTaskConfig config) {
		Optional<DaemonTask> optioanl = Optional.empty();
        ServiceLoader<DaemonTask> daemonTasks = ServiceLoader.load(DaemonTask.class);
        for (DaemonTask daemonTask : daemonTasks) {
            if (daemonTask.supports(config.getType())) {
            	optioanl = Optional.of(daemonTask.setConfig(config));
            }
        }
        if (!optioanl.isPresent()) {
            throw new RuntimeException("不支持线程任务类型【" + config.getType() + "】");
        }
        return optioanl.get();
    }
}
