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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * Implementation for the ILogPublisher interface that contains a Formatter for the LogRecords.
 * <p>
 * As default SimpleFormatter from the java.logging API is used.
 * <p><p>
 * Contains two default implementations ConsolePublisher and FilePublisher.
 * 
 * @author Jimmy
 *
 */
public abstract class LogPublisher implements ILogPublisher {
	
	protected Formatter formatter = null;
	
	public LogPublisher() {
		formatter = new LogFormatter();
	}
	
	public LogPublisher(Formatter formatter) {
		this.formatter = formatter;
	}
	
	public Formatter getFormatter() {
		return formatter;
	}
	
	public void setFormatter(Formatter formatter) {
		this.formatter = formatter;
	}

	@Override
	public abstract void close() throws SecurityException;

	@Override
	public abstract void flush();
	
	public abstract void publish(String formattedMsg);

	@Override
	public void publish(LogRecord record) {
		Formatter actualFormatter = formatter;
		if (actualFormatter != null) publish(actualFormatter.format(record));
	}
	
	//
	// Follows simple implementation of publishers
	//
	
	public static class ConsolePublisher extends LogPublisher {

		@Override
		public void close() throws SecurityException {
		}

		@Override
		public void flush() {
		}

		@Override
		public void publish(String formattedMsg) {
			System.out.println(formattedMsg);
		}
		
	}
	
	public static class FilePublisher extends LogPublisher {
		
		protected File file;
		protected FileOutputStream fileOut;
		protected PrintWriter fileWriter;
		
		public FilePublisher(File file) throws IOException {
			super();
			this.file = file;
			
			fileOut = new FileOutputStream(file);
			fileWriter = new PrintWriter(fileOut);
		}
		
		public FilePublisher(File file, Formatter formatter) {
			super(formatter);
		}
		
		public File getFile() {
			return file;
		}

		@Override
		public void close() throws SecurityException {
			fileWriter.close();
			try {
				fileOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void flush() {
			fileWriter.flush();
			try {
				fileOut.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void publish(String formattedMsg) {
			fileWriter.println(formattedMsg);
		}
		
	}

}
