/*
 * 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.vw.infrastructure.log;

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;
import com.scytl.products.ov.vw.services.domain.model.platform.VwLoggingKeystoreRepository;

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

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

    private static final String context = "VW";

    private static final String encryptionPwPropertiesKey = "VW_log_encryption";

    private static final String signingPwPropertiesKey = "VW_log_signing";

    @EJB
    @VwLoggingKeystoreRepository
    LoggingKeystoreRepository loggingKeystoreRepository;

    @EJB
    VwLoggingInitializationState vwLoggingInitializationState;

    /**
     * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.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(vwLoggingInitializationState,
            loggingKeystoreRepository, context, encryptionPwPropertiesKey, signingPwPropertiesKey);

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

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

    }
}
