package com.eactive.eai.common.testcall;

import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.common.errorcode.ErrorCodeHandler;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;

public class TestCallRunner extends TimerTask {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	private TestCallManager manager;

	// TestCallRunner 동작 시 INFO 메시지에 대한 코드
	private static final String START_MSGCODE = "RICEAICTR001";
	// TestCallRunner 동작 시 발생되는 오류에 대한 코드
	private static final String ERROR_MSGCODE = "RECEAICTR002";

	public void setTestCallManager(TestCallManager manager) {
		this.manager = manager;
	}

	public void run() {
		String msg = ErrorCodeHandler.getMessage(START_MSGCODE, new String[] { Thread.currentThread().getName() });
		logger.warn("TestCallRunner] " + msg);
		
		if (this.manager == null || !this.manager.isStarted()) {
			logger.warn("TestCallManager is stopped. stop TestCallRunner.");
			return;
		}
		
		Iterator<String> adapterNames = manager.getAllAdapterNames();
		
		ExecutorService executor = Executors.newFixedThreadPool(10);
		try {
			while (adapterNames.hasNext()) {			
				String name = adapterNames.next();
				TestCall testObj = manager.getTestCall(name);
				AdapterVO vo = testObj.getAdapterInfo();
				if (testObj == null || vo.isStatus()) {
					manager.removeTestCall(name);
					continue;
				}
				
				executor.submit(() -> {
					try {
						if (testObj.isAlive()) {
							manager.removeTestCall(name);
							vo.setStatus(true);					
						}
					} catch (Exception e) {
						String[] args = { testObj.getAdapterInfo().toString(), e.getMessage() };
						if (logger.isError()) {
							logger.error(ExceptionUtil.make(ERROR_MSGCODE, args), e);
						}
					}
		        });
			}
		}
		finally {
			executor.shutdown();
		}
	}
}
