/*
 * 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.channel.cc.orchestrator.infrastructure.logging;

import com.scytl.products.ov.channel.cc.orchestrator.domain.platform.OrchestratorLoggingKeystoreRepository;
import javax.ejb.EJB;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scytl.products.ov.commons.logging.config.SecureLoggerInitializer;
import com.scytl.products.ov.commons.logging.domain.model.LoggingKeystoreRepository;

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

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

    private static final String CONTEXT = "OR";

    private static final String ENCRYPTION_PWS_PROPERTIES_KEY = "OR_log_encryption";

    private static final String SIGNING_PWS_PROPERTIES_KEY = "OR_log_signing";
    
    @EJB
    @OrchestratorLoggingKeystoreRepository
    LoggingKeystoreRepository loggingKeystoreRepository;

    @EJB
    OrchestratorLoggingInitializationState orchestratorLoggingInitializationState;

    /**
     * @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(
                orchestratorLoggingInitializationState,
            loggingKeystoreRepository, CONTEXT, ENCRYPTION_PWS_PROPERTIES_KEY, SIGNING_PWS_PROPERTIES_KEY);

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

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

    }
}
