package eu.dnetlib.functionality.modular.ui;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import eu.dnetlib.functionality.modular.ui.utils.LogLine;
import eu.dnetlib.functionality.modular.ui.utils.LogUiAppender;

@Controller
public class DnetLogAjaxController {

	private LogUiAppender appender;

	private static final Log log = LogFactory.getLog(DnetLogAjaxController.class);

	@PostConstruct
	void init() throws IOException {
		this.appender = findLogUiAppender();
	}

	private LogUiAppender findLogUiAppender() {
		final Logger logger = LogManager.getRootLogger();
		final Enumeration<?> appenders = logger.getAllAppenders();
		while (appenders.hasMoreElements()) {
			final Object app = appenders.nextElement();
			if (app instanceof LogUiAppender) {
				log.info("An istance of LogUiAppender is already registered in log4j configuration.");
				return (LogUiAppender) app;
			}
		}

		final LogUiAppender app = new LogUiAppender();
		LogManager.getRootLogger().addAppender(app);

		log.info("A new LogUiAppender has been registered in log4j configuration.");

		return app;
	}

	@RequestMapping(value = "/ui/log/tail/{n}")
	public @ResponseBody
	List<LogLine> tail_N(@PathVariable(value = "n") final int n) throws Exception {
		return appender.tail_N(n);
	}

	@RequestMapping(value = "/ui/log/continue/{after}")
	public @ResponseBody
	List<LogLine> tail_continue(@PathVariable(value = "after") final int after) throws Exception {
		return appender.tail_continue(after);
	}

	@RequestMapping(value = "/ui/log/level/{level}/{resource}")
	public @ResponseBody
	boolean updateLogLevel(@PathVariable(value = "level") final String level, @PathVariable(value = "resource") final String resource) throws Exception {
		if (resource != null && level != null) {
			LogManager.getLogger(resource).setLevel(Level.toLevel(level));
		}
		return true;
	}

}
