package org.biomoby.registry.sync.logging;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * Class to initialise the logger.
 * 
 * @author groscurt
 * 
 */
public class MobySecondaryLogging {
	// to avoid repeated initialisation
	private static boolean isInit = false;

	public static final String LOGGER_NAME = "mobysync";

	/**
	 * Avoid instantiation of the class
	 */
	private MobySecondaryLogging() {
	}

	/**
	 * Inits the logger. The log file is stored in the given logpath and has the following
	 * structure:
	 * <p>
	 * MobySecondaryLog-mmdd-yy-hh_mm
	 * </p>
	 * 
	 * @param logFilepath
	 *            the path where the logfiles are stored
	 * @param level
	 *            the log level (info, warning, severe)
	 * @throws IOException
	 *             whether the initialisation of the logger failed
	 */
	public static void initLogger( String logFilepath, String level ) throws IOException {
		Logger logger = Logger.getLogger( LOGGER_NAME );

		// we dont want to have the log infos on the console
		logger.setUseParentHandlers(false);
		
		// dont do the same work again
		if ( isInit ) {
			return;
		}

		// if the directory / misses add it
		if ( !logFilepath.endsWith( "/" ) ) {
			logFilepath += "/";
		}

		Calendar calendar = new GregorianCalendar();
		// log files will be created based on mm-dd-yyyy-hh_mm
		String logFile = "MobySecondaryLog-" + ( calendar.get( Calendar.MONTH ) + 1 ) + "-"
				+ calendar.get( Calendar.DAY_OF_MONTH ) + "-" + calendar.get( Calendar.YEAR ) + "-"
				+ calendar.get( Calendar.HOUR_OF_DAY ) + "_" + calendar.get( Calendar.MINUTE );
		FileHandler fh = new FileHandler( logFilepath + logFile + ".log", true );
		
		
		// create a formatter which adds a newline to each logrecord
		fh.setFormatter( new SimpleFormatter() {
			public synchronized String format( LogRecord record ) {
				String s = super.format( record ) + System.getProperty( "line.separator" );
				return s;
			}
		} );
		logger.addHandler( fh );
		logger.setLevel( Level.parse( level.toUpperCase().trim() ) );

		logger.fine( "Logger was initialised !" );

		isInit = true;
	}
}
