package com.avaya.customer.example.servlet;

import com.avaya.customer.example.servlet.utils.Configuration;
import com.avaya.customer.example.servlet.utils.Constants;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebListener;

@WebListener
public class ContextListener extends ResteasyBootstrap {
    private static final Logger LOG = LoggerFactory.getLogger(ContextListener.class);

    public static Configuration appConfig;

    /**
     * Initialize application.
     */
    @Override
    public void contextInitialized(ServletContextEvent event) {
        // initialize Resteasy
        super.contextInitialized(event);

        // initialize log4j here
        ServletContext context = event.getServletContext();
        String log4jConfigFile = context.getInitParameter("log4j-config-location");
        LoggerContext loggerContext = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
        File file = new File(context.getRealPath("") + File.separator + log4jConfigFile);
        if (file.exists()) {
            loggerContext.setConfigLocation(file.toURI());
        }

        // initialize constants
        new Constants(context);

        // initialize configuration
        File propertiesFile = new File(Constants.propsPath);

        // If no properties file exists yet, copy the sample file into place
        if (!propertiesFile.exists()) {
            try {
                Files.copy(new File(getClass().getClassLoader().getResource("oceana.properties.sample").getFile()), propertiesFile);
            } catch (IOException e) {
                LOG.info("Error deploying default properties file", e);
            }
        }

        appConfig = new Configuration(propertiesFile);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        super.contextDestroyed(event);
    }
}