package tutorial;

import java.lang.management.ManagementFactory;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import kr.fujitsu.com.ffw.daemon.LogPropertySetter;
import kr.fujitsu.com.ffw.daemon.core.CurrentContext;
import kr.fujitsu.com.ffw.daemon.core.DaemonConfigLocator;
import kr.fujitsu.com.ffw.daemon.core.config.log.Log;
import kr.fujitsu.com.ffw.daemon.core.config.node.EngineContainer;
import kr.fujitsu.com.ffw.daemon.net.ActionFactory;
import kr.fujitsu.com.ffw.daemon.net.DaemonContainer;
import kr.fujitsu.com.ffw.daemon.net.logger.AccessLogFactory;
import kr.fujitsu.com.ffw.daemon.net.logger.AccessLogger;
import kr.fujitsu.com.ffw.daemon.net.server.ActionServerContainer;
import kr.fujitsu.com.ffw.daemon.net.server.ServerAction;

import org.apache.log4j.Logger;

public class TestContainerServer extends DaemonContainer {
	private static Logger logger = Logger
			.getLogger(ActionServerContainer.class);
	private static DaemonConfigLocator locator = null;
	

    static String logFile = "D:\\project\\pb\\SPC_NextHS_DOC\\sms-1.0.1\\log4j.xml";
    static Log log = null;

	public TestContainerServer(EngineContainer context) throws Exception {
		super(context);
	}

	public void loop() {
		System.out.println("▷▶ ActionServerContainer is listening to request ... ");
		int readTimeout = 0;
		ServerAction action = null;
		Socket clntSock = null;
		AccessLogger access = null;
		try {
			access = AccessLogFactory.createLogger(super.getContext());
			clntSock = super.getServerSocket().accept();
			access.initialize(super.getServerSocket(), clntSock);

			readTimeout = toInt(getContext().getTcpConfiguration()
					.getReadTimeout());
			if (readTimeout > 0) {
				System.out.println(">>> readTimeout in ActionServerContainer is setting up to "
						+ readTimeout + "ms");
				clntSock.setSoTimeout(readTimeout);
			}
			action = (ServerAction) ActionFactory.createAction(locator
					.getCurrentContext().getContext().getAction());
			action.setSocket(clntSock);

			getPool().execute(action);
			System.out.println(getPool().getStatus());
		} catch (Exception e) {
			System.out.println(e.getStackTrace().toString());
			access.error(e);
		}
	}

	public void initialize() {
		try {
			System.out.println("initialized container...");
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public void destroy() {
		System.out.println("▷▶ ActionServerContainer meets destroy request ... ");
		try {
			if (getPool() != null)
				getPool().close();
			if (!(getServerSocket().isClosed()))
				getServerSocket().close();
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public static void main(String[] args) throws Exception {
		String containerName = "cms_JournalRcv";
		String mode = "xml";
		String path = "D:\\project\\pb\\SPC_NextHS_DOC\\sms-1.0.1\\xml\\daemon-config.xml".replaceFirst("-path:", "");
		
		
		System.out.println("DaemonL... PID :" + ManagementFactory.getRuntimeMXBean().getName().split("@")[0] );
		
		try{
			locator = DaemonConfigLocator.getInstance(mode, path);
			locator.setCurrentContext(new CurrentContext(locator.getDaemonConfig()
					.getNode().getEngineContainer(containerName)));
	
			DaemonContainer container = new ActionServerContainer(locator
					.getCurrentContext().getContext());
			
	
	        log = DaemonConfigLocator.getInstance().getDaemonConfig().getLog();
	        LogPropertySetter.writeLog4JConfigXml(logFile, log);
	        LogPropertySetter.loadLog4JConfigFile(logFile);
	        
			Thread t = new Thread(container);
			t.start();
		
		
		}catch(Exception i){
			System.out.println("[ERROR] " + i.getStackTrace().toString());
		}
	}

	public class StopWatch {
		private final int MILLIS_IN_SECOND = 1000;

		private final int MILLIS_IN_MINUTE = 60000;

		private final int MILLIS_IN_HOUR = 3600000;

		private long startTime = -1L;

		private long stopTime = -1L;

		public String start() {
			this.stopTime = -1L;
			this.startTime = System.currentTimeMillis();
			Calendar cal = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat(
					"yyyy.MM.dd HH:mm:ss,SSS");
			return sdf.format(cal.getTime());
		}

		public void stop() {
			this.stopTime = System.currentTimeMillis();
		}

		public void reset() {
			this.startTime = -1L;
			this.stopTime = -1L;
		}

		public void split() {
			this.stopTime = System.currentTimeMillis();
		}

		public void unsplit() {
			this.stopTime = -1L;
		}

		public void suspend() {
			this.stopTime = System.currentTimeMillis();
		}

		public void resume() {
			this.startTime += System.currentTimeMillis() - this.stopTime;
			this.stopTime = -1L;
		}

		public long getTime() {
			if (this.stopTime == -1L) {
				if (this.startTime == -1L) {
					return 0L;
				}
				return (System.currentTimeMillis() - this.startTime);
			}
			return (this.stopTime - this.startTime);
		}

		public String toString() {
			return formatISO(getTime());
		}

		public String formatISO(long millis) {
			int hours = (int) (millis / 3600000L);
			millis -= hours * 3600000;
			int minutes = (int) (millis / 60000L);
			millis -= minutes * 60000;
			int seconds = (int) (millis / 1000L);
			millis -= seconds * 1000;
			int milliseconds = (int) millis;

			StringBuffer buf = new StringBuffer(32);
			buf.append(hours);
			buf.append(':');
			buf.append((char) (minutes / 10 + 48));
			buf.append((char) (minutes % 10 + 48));
			buf.append(':');
			buf.append((char) (seconds / 10 + 48));
			buf.append((char) (seconds % 10 + 48));
			buf.append('.');

			if (milliseconds < 10)
				buf.append('0').append('0');
			else if (milliseconds < 100) {
				buf.append('0');
			}

			buf.append(milliseconds);
			return buf.toString();
		}
	}
}


