package cz.cuni.amis.pogamut.base.utils.logging;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * Pogamut custom formatter used for LogPublishers as default.
 * <p><p>
 * <b>WARNING:</b> log record parameters are written from index 1 not 0 because at the 0-th index is the LogCategory instance.
 * @author Jimmy
 *
 */
public class LogFormatter extends Formatter {
	
	private SimpleDateFormat yearDateFormat = new SimpleDateFormat("y");
	private SimpleDateFormat monthDateFormat = new SimpleDateFormat("M");
	private SimpleDateFormat dayDateFormat = new SimpleDateFormat("d");
	private SimpleDateFormat timeFormat = new SimpleDateFormat("H:m:s.S");
	
	private StringBuffer buffer = new StringBuffer(512);

	@Override
	public String format(LogRecord record) {
		buffer.delete(0, buffer.length());
		Date date = new Date(record.getMillis());
		buffer.append(yearDateFormat.format(date));
		buffer.append("-");		
		String month = monthDateFormat.format(date);
		if (month.length() > 1) buffer.append(month);
		else {
			buffer.append("0");
			buffer.append(month);		
		}		 
		buffer.append("-");
		String day = dayDateFormat.format(date);
		if (day.length() > 1) buffer.append(day);
		else {
			buffer.append("0");
			buffer.append(day);		
		}		 
		buffer.append(" ");
		buffer.append(timeFormat.format(date));
		buffer.append(" ");
		buffer.append(record.getLoggerName());
		buffer.append("\r\n");
		buffer.append(record.getLevel().toString());
		buffer.append(": ");
		buffer.append(record.getMessage());
//		if (record.getParameters() != null) {
//			for (int i = 1; i < record.getParameters().length; ++i) {
//				buffer.append("\r\n");
//				buffer.append("Param ");
//				buffer.append(i);
//				buffer.append(": ");
//				buffer.append(String.valueOf(record.getParameters()[i]));
//			}
//		}
		return buffer.toString();
	}

}
