/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.ea.services.infrastructure.logging;

import com.scytl.products.ov.commons.logging.config.SecureLoggerInitializer;
import com.scytl.products.ov.commons.logging.domain.model.LoggingKeystoreRepository;
import com.scytl.products.ov.ea.services.domain.model.platform.EaLoggingKeystoreRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.EJB;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Defines any steps to be performed when the EA context is first initialized and destroyed.
 */
public class EaContextListener implements ServletContextListener {

    private static final Logger LOG = LoggerFactory.getLogger("std");

    private static final String CONTEXT = "EA";

    private static final String ENCRYPTION_PW_PROPERTIES_KEY = "EA_log_encryption";

    private static final String SIGNING_PW_PROPERTIES_KEY = "EA_log_signing";

    @EJB
    @EaLoggingKeystoreRepository
    LoggingKeystoreRepository loggingKeystoreRepository;

    @EJB
    EaLoggingInitializationState eaLoggingInitializationState;

    /**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    @Override
    public void contextInitialized(final ServletContextEvent servletContextEvent) {

        LOG.info(CONTEXT + " - context initialized, will attempt to initialize logging if data exists in DB");

        SecureLoggerInitializer secureLoggerInitializer = new SecureLoggerInitializer(eaLoggingInitializationState,
            loggingKeystoreRepository, CONTEXT, ENCRYPTION_PW_PROPERTIES_KEY, SIGNING_PW_PROPERTIES_KEY);

        if (secureLoggerInitializer.initializeIfDataExistsInDB()) {
            LOG.info(CONTEXT + " - initialized logging correctly from DB");
            eaLoggingInitializationState.setInitialized(true);
        } else {
            LOG.info(CONTEXT + " - logging not initialized - did not find keystores in DB");
        }
    }

    /**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    @Override
    public void contextDestroyed(final ServletContextEvent sce) {

    }
}
