package kr.gmtc.tss.status;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;

@Component
@Scope("singleton")
public class ContextDestroyStatus {
	/**
	 * Logger.
	 */
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	/**
	 * linstener list.
	 */
	private final List<ContextDestroyEventListener> contextDestroyEventListeners = new ArrayList<ContextDestroyEventListener>();
	
	/**
	 * context destroy 여부 상태 값.
	 */
	private boolean shutdown = false;
	
	/**
	 * Shutdown flag 설정 등. 등록된 listener의 onDestroy event를 fire 한다.
	 */
	@PreDestroy
	public void destroy() {
		logger.info("Called destroy()!");
		shutdown = true;
		
		for (ContextDestroyEventListener listener : contextDestroyEventListeners) {
			listener.onDestroy();
		}
	}
	
	/**
	 * @return destroy 된다면 true. 동작 중에는 false.
	 */
	public boolean getShutdownStat() {
		return shutdown;
	}
	public void setShutdownStat(boolean shutdown ) {
		this.shutdown=shutdown;
//		return shutdown;
	}
	
	
	/**
	 * @param listener
	 *            event fire 대상 class.
	 */
	public void addListener(final ContextDestroyEventListener listener) {
		contextDestroyEventListeners.add(listener);
		logger.info("addListener ({}) complete. Listeners count is {}.", listener.getClass().getName(),
				contextDestroyEventListeners.size());
	}
}
