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

import java.util.List;

import org.springblade.etl.task.contants.TaskConstant;
import org.springblade.etl.task.model.DaemonTaskConfig;
import org.springblade.etl.task.service.DaemonTask;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 */
@Slf4j
public class DaemonFactory {

	/**
	 * 启动
	 * 
	 * @param configList
	 */
	public static void start(List<DaemonTaskConfig> configList) {
		Thread thread = new Thread(() -> {
			EtlThreadPool etlThreadPool = EtlThreadPool.getInstance();
			for (DaemonTaskConfig config : configList) {
//				DaemonTask daemonTask = config.getType().ofService();
				DaemonTask daemonTask = DaemonTask.ofService(config);
				if(daemonTask != null) {
					daemonTask.setConfig(config);
					etlThreadPool.execute(daemonTask);
				}
			}
			while (true) {
				int taskSize = etlThreadPool.getTaskSize();
				try {
					Thread.sleep(Math.max(TaskConstant.MAX_POLLING_GAP / (taskSize + 1), TaskConstant.MIN_POLLING_GAP));
				} catch (InterruptedException e) {
					log.error(e.getMessage(), e);
				}
				int num = taskSize / 100 + 1;
				if (etlThreadPool.getWorkCount() < num) {
					etlThreadPool.addWorkers(num - etlThreadPool.getWorkCount());
				} else if (etlThreadPool.getWorkCount() > num) {
					etlThreadPool.removeWorker(etlThreadPool.getWorkCount() - num);
				}
			}
		});
		thread.start();
		log.info("自定义任务线程池扩缩容管理线程已启动....");
	}

	/**
	 * 添加任务
	 * @param config
	 */
	public static void addTask(DaemonTaskConfig config) {
		log.info("添加一个监控任务|id={},type={}", config.getId(), config.getType());
		DaemonTask daemonTask = DaemonTask.ofService(config);
		if(daemonTask != null) {
			daemonTask.setConfig(config);
			EtlThreadPool.getInstance().execute(daemonTask);
		}
	}
	
	/**
	 * 
	 */
	public static void shutdown() {
		EtlThreadPool instance = EtlThreadPool.getInstance();
		log.info("正在停止线程池|taskNum={},threadNum={}", instance.getTaskSize(), instance.getWorkCount());
		instance.shutdown();
	}
}
