package com.eactive.eai.transformer.util;

import com.eactive.eai.common.property.PropGroupVO;
import com.eactive.eai.common.property.PropManager;


public class MemoryLogger {
	static final int MAX_LOG_MESSAGE_SIZE = 500000;
	
	// Memory 문제로 100 -> 20 줄임
	static CircularQueue txQueue = new CircularQueue(20);
	static CircularQueue errorQueue = new CircularQueue(20);
	static long errorCount = 0;
	
	private MemoryLogger() {
		
	}
	public static int getTransactionCount() {
		return txQueue.getRecordCount();
	}
	
	public static String[] getTransactions() {
		return txQueue.getRecords();
	}
	
	public static boolean isMemoryLogEnabled() {
    	PropGroupVO propGroupVO = PropManager.getInstance().getPropGroupVO("Transformer");
    	if (propGroupVO == null)
    		return false;
    	String value = propGroupVO.getProperty("memory.log");
    	return ("1".equals(value));
	}

	public static void txlog(String message) {
		if (message == null)
			return;
		if (message.length() > MAX_LOG_MESSAGE_SIZE)
			message = message.substring(0, MAX_LOG_MESSAGE_SIZE);
		
		txQueue.addRecord(message);
	}
	
	public static long getErrorCount() {
		return errorCount;
	}
	
	public static String[] getErrors() {
		return errorQueue.getRecords();
	}

	public static void error(String message) {
		if (message == null)
			return;
		if (message.length() > MAX_LOG_MESSAGE_SIZE)
			message = message.substring(0, MAX_LOG_MESSAGE_SIZE);
		
		synchronized(MemoryLogger.class) {
			errorCount++;
		}
		errorQueue.addRecord(message);
		txQueue.addRecord("<font color='blue'>" + message + "</font>");
	}

	public static void error(String message, Throwable t) {
		if (message == null)
			return;
		if (message.length() > MAX_LOG_MESSAGE_SIZE)
			message = message.substring(0, MAX_LOG_MESSAGE_SIZE);
		
		synchronized(MemoryLogger.class) {
			errorCount++;
		}
		errorQueue.addRecord(message + " | " + ExceptionStackTrace.dump(t));
		txQueue.addRecord("<font color='blue'>" + message + "\n" + ExceptionStackTrace.dump(t) + "</font>");
	}
}
