package de.tu_dresden.diplom.richter_mirko_mat2628335;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.ConfigurationException;

import javax.servlet.http.HttpServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

/**
 * 
 */
public class Startup extends HttpServlet{

   private static final Logger logger = Logger.getLogger(Startup.class);

   private static Configuration config = null;

   public void init(ServletConfig servletConfig) throws ServletException {
         String applicationConf = servletConfig.getInitParameter("acpConfFile");
         if (applicationConf == null || applicationConf.length() == 0) {
            System.out.println("********************\nNo Application-Conf-File given... Leaving it blank!\n********************");
            config = new PropertiesConfiguration();
         } else {
            try {
               config = new PropertiesConfiguration(servletConfig.getServletContext().getRealPath(applicationConf));
            } catch (ConfigurationException e) {
               e.printStackTrace();
            }
            if (!config.containsKey("acpProject.absoluteConfHome")) {
               config.setProperty("acpProject.absoluteConfHome", servletConfig.getServletContext().getRealPath(config.getString("acpProject.relativeConfHome")));
            } else {

            }
            initLog4j(config);
         }
         config.setProperty("acpProject.web_inf.dir", servletConfig.getServletContext().getRealPath("/WEB-INF"));
      }

      private void initLog4j(Configuration config) {
         String fn = "[initializeLog4J]";
         String log4jConfFilePath = config.getString("acpProject.absoluteConfHome") + "/" + config.getString("acpProject.log4j.configuration.file");
         System.out.println("Startup: Initializing Log4J with file '" + log4jConfFilePath + "'");
         PropertyConfigurator.configure(log4jConfFilePath);
         logger.info(fn + " Logger is up and running!");
      }

   public static Configuration getConfig(){
      return config;
   }

}
