/****************************************************************************
 * Copyright Avaya Inc., All Rights Reserved.
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Avaya Inc.
 * The copyright notice above does not evidence any actual or intended publication of such source code.
 * Some third-party source code components may have been modified from their original versions by Avaya Inc.
 * The modifications are Copyright Avaya Inc., All Rights Reserved.
 * Avaya Confidential & Restricted. May not be distributed further without written permission of
 * the Avaya owner.
 ****************************************************************************/
package com.avaya.zephyr.services.sample_services.Authorization.util;

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

import org.apache.commons.lang3.StringUtils;

import com.avaya.asm.datamgr.DMFactory;
import com.avaya.asm.datamgr.DMListener;
import com.avaya.collaboration.businessdata.api.NoAttributeFoundException;
import com.avaya.collaboration.businessdata.api.ServiceData;
import com.avaya.collaboration.businessdata.api.ServiceNotFoundException;
import com.avaya.collaboration.dal.factory.CollaborationDataFactory;
import com.avaya.collaboration.util.logger.Logger;
import com.avaya.zephyr.platform.dal.api.ServiceUtil;
import com.avaya.zephyr.platform.dao.AusServiceDAO;
import com.avaya.zephyr.services.sample_services.Authorization.listener.AttributeChangeListener;

@WebListener
public class ServiceAttributesInitializer implements ServletContextListener
{
    private final ServiceAttributeStore serviceAttributeStore;
    private final DMListener attributeChangeListener;
    private final DMFactory dmFactory;
    private final ServiceData serviceData;

    private final Logger logger;

    public ServiceAttributesInitializer()
    {
        this(ServiceAttributeStore.getInstance(), new AttributeChangeListener(),
                CollaborationDataFactory.getServiceData(ServiceUtil.getServiceDescriptor().getName(),
                        ServiceUtil.getServiceDescriptor().getVersion()),
                DMFactory.getInstance(), Logger.getLogger(ServiceAttributesInitializer.class));
    }

    ServiceAttributesInitializer(final ServiceAttributeStore serviceAttributeStore, final DMListener attributeChangeListener,
            final ServiceData serviceData, final DMFactory dmFactory, final Logger logger)
    {
        this.serviceAttributeStore = serviceAttributeStore;
        this.attributeChangeListener = attributeChangeListener;
        this.serviceData = serviceData;
        this.dmFactory = dmFactory;
        this.logger = logger;
    }

    @Override
    public void contextInitialized(final ServletContextEvent arg0)
    {
        logger.finer("ServiceAttributesInitializer: init");

        setEnableTokenlessAccess();
        setSessionCookieName();
        setClientRedirectionPath();

        dmFactory.getDataMgr(AusServiceDAO.class).registerListener(attributeChangeListener);
    }

    private void setClientRedirectionPath()
    {
        final String clientRedirectionPath = readServiceAttribute(ServiceAttributeDefaults.CLIENT_REDIRECTION_PATH.getAttributeName());
        if (StringUtils.isNotBlank(clientRedirectionPath))
        {
            serviceAttributeStore.setClientRedirectionPath(clientRedirectionPath);
        }
        else
        {
            serviceAttributeStore.setSessionCookieName(ServiceAttributeDefaults.CLIENT_REDIRECTION_PATH.getDefaultValue());
        }
    }

    private void setSessionCookieName()
    {
        final String sessionCookieName = readServiceAttribute(ServiceAttributeDefaults.SESSION_COOKIE_NAME.getAttributeName());
        if (StringUtils.isNotBlank(sessionCookieName))
        {
            serviceAttributeStore.setSessionCookieName(sessionCookieName);
        }
        else
        {
            serviceAttributeStore.setSessionCookieName(ServiceAttributeDefaults.SESSION_COOKIE_NAME.getDefaultValue());
        }
    }

    private void setEnableTokenlessAccess()
    {
        final String enableTokenlessAccess = readServiceAttribute(ServiceAttributeDefaults.ENABLE_TOKENLESS_ACCESS.getAttributeName());
        if (StringUtils.isNotBlank(enableTokenlessAccess))
        {
            serviceAttributeStore.setEnableTokenlessAccess(Boolean.valueOf(enableTokenlessAccess));
        }
        else
        {
            serviceAttributeStore.setEnableTokenlessAccess(Boolean.valueOf(ServiceAttributeDefaults.ENABLE_TOKENLESS_ACCESS
                    .getDefaultValue()));
        }
    }

    private String readServiceAttribute(final String attributeName)
    {
        try
        {
            return serviceData.getServiceAttribute(attributeName);
        }
        catch (final NoAttributeFoundException e)
        {
            logger.error("ServiceAttributesInitializer readServiceAttribute : " +
                    "Error while retrieving value of attribute " + attributeName + "," + e.getMessage());
        }
        catch (final ServiceNotFoundException e)
        {
            logger.error("ServiceAttributesInitializer readServiceAttribute : Service not found ", e);
        }
        return null;
    }

    @Override
    public void contextDestroyed(final ServletContextEvent arg0)
    {
        logger.finer("ServiceAttributesInitializer: destroy");
        dmFactory.getDataMgr(AusServiceDAO.class).removeListener(attributeChangeListener);
    }
}
