package com.videonext.mplayer.internal;

import java.util.logging.Formatter;
import java.util.logging.LogRecord;


public class LogFormatter extends Formatter {
	protected String playerId;

	public LogFormatter(String playerId) {
		this.playerId = playerId;
	}


	@Override
	public String format(LogRecord record) {
		// truncate class name
		String className = record.getSourceClassName();
		int i = record.getSourceClassName().lastIndexOf('.');
		if (i != -1) {
			className = className.substring(i + 1); 
		}

		Throwable t = record.getThrown();				
		if (t == null)
			return String.format("%1$tH:%1$tM:%1$tS.%1$tL %2$s [%3$s] %4$s\n",
				record.getMillis(), record.getLevel(), playerId, trimMessage(record.getMessage()));
		else {
			String tMsg = t.getMessage();
			if (tMsg == null) {
				tMsg = t.getClass().getName();
			}

			// format stack trace
			StringBuilder stackTrace = new StringBuilder();
			if (!(t instanceof java.net.SocketException)) {
				StackTraceElement[] elements = t.getStackTrace();
				if (elements != null && elements.length > 0) {
					stackTrace.append("\n");
					for(int e = 0; e < elements.length; e++) {
						stackTrace.append(elements[e].toString());
						stackTrace.append("\n");
					}
				}
			}
			
			Throwable cause = t.getCause();
			if (cause != null) {
				stackTrace.append(" Caused by ");
				stackTrace.append(cause.getClass().getName());
				stackTrace.append(" - ");
				stackTrace.append(cause.getMessage());
			}
			
			return String.format("%1$tH:%1$tM:%1$tS.%1$tL %2$s [%3s] %4$s:%5$s %6$s/%7$s%8$s\n",
					record.getMillis(), record.getLevel(), playerId, className,
					record.getSourceMethodName(), trimMessage(record.getMessage()),
					tMsg, stackTrace.toString());
			}
	}
	
	
	private String trimMessage(String str) {
		int len = str.length() - 1;
		int i = len;
		while (i >= 0 && " \n\r\t\f".indexOf(str.charAt(i)) != -1) i--;
		
		if (i == len) {
			return str;
		} else if (i == -1) {
			return "";
		} else {
			return str.substring(0, i + 1);
		}
	}
}
