package cn.citycraft.AuthMe;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import com.google.common.base.Throwables;

import cn.citycraft.AuthMe.settings.Settings;
import fr.xephi.authme.api.NewAPI;

public class ConsoleLogger {

	private static final DateFormat df = new SimpleDateFormat("[MM-dd HH:mm:ss]");
	private static final Logger log = AuthMe.getInstance().getLogger();

	public static void info(final String message) {
		if (AuthMe.getInstance().isEnabled()) {
			log.info(message);
			if (Settings.useLogging) {
				String dateTime;
				synchronized (df) {
					dateTime = df.format(new Date());
				}
				writeLog(dateTime + " " + message);
			}
		}
	}

	public static void showError(final String message) {
		if (AuthMe.getInstance().isEnabled()) {
			log.warning(message);
			if (Settings.useLogging) {
				String dateTime;
				synchronized (df) {
					dateTime = df.format(new Date());
				}
				writeLog(dateTime + " ERROR: " + message);
			}
		}
	}

	public static void writeLog(final String message) {
		try {
			Files.write(Settings.LOG_FILE.toPath(), (message + NewAPI.newline).getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
		} catch (final IOException ignored) {
		}
	}

	public static void writeStackTrace(final Exception ex) {
		String dateTime;
		synchronized (df) {
			dateTime = df.format(new Date());
		}
		writeLog(dateTime + " " + Throwables.getStackTraceAsString(ex));
	}
}
