package com.avaya.services.whitelist.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

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;

public final class PersitanceUnitProperties {
	private final ServiceData serviceData;
	public static final String FACTORY_CLASS = "org.hibernate.transaction.JDBCTransactionFactory";
	public static final String DATA_CACHE = "true";
	public static final String QUERY_CACHE = "true(CacheSize=1000, SoftReferenceSize=0)";

    public static final String DB_TYPE_ATTRIBUTE = "dbType";
    public static final String DB_URL_ATTRIBUTE = "dbUrl";
    public static final String DB_USERNAME_ATTRIBUTE = "dbUsername";
    public static final String DB_PASSWORD_ATTRIBUTE = "dbPassword";
    public static final String DB_MAXACTIVE_ATTRIBUTE = "maxActive";
    public static final String DB_MAXWAIT_ATTRIBUTE = "maxWait";

    public static final String POSTGRES_DB_TYPE = "postgres";
    public static final String MYSQL_DB_TYPE = "mysql";
    private final Logger logger; // NOSONAR

    public static final String JTA_DATA_SOURCE = "datasourceJNDIName";

	public PersitanceUnitProperties() {
		this(CollaborationDataFactory.getServiceData(ServiceUtil
				.getServiceDescriptor().getName(), ServiceUtil
				.getServiceDescriptor().getVersion()), Logger
				.getLogger(PersitanceUnitProperties.class));
	}

	PersitanceUnitProperties(final ServiceData serviceData, final Logger logger) {
		this.serviceData = serviceData;
		this.logger = logger;
	}

	Map<String, String> getPersistanceUnitMap()
			throws NoAttributeFoundException, ServiceNotFoundException {
		final Map<String, String> persistenceProperties = new HashMap<String, String>();

        persistenceProperties.put("javax.persistence.jtaDataSource", getJNDIName());

		persistenceProperties.put("transaction.factory_class", FACTORY_CLASS);

		persistenceProperties.put("openjpa.DataCache", DATA_CACHE);
		persistenceProperties.put("openjpa.QueryCache", QUERY_CACHE);

		final String testOnBorrow = "true";
		persistenceProperties.put("openjpa.ConnectionTestOnBorrow",
				testOnBorrow);
		return persistenceProperties;
	}

    private String getJNDIName() throws NoAttributeFoundException, ServiceNotFoundException
    {
        final String defaultJNDIName = "jdbc/whitelist";
        String jndiName = defaultJNDIName;

        final String jtaDataSource = serviceData.getServiceAttribute(JTA_DATA_SOURCE);
        if (!StringUtils.isBlank(jtaDataSource))
        {
            jndiName = jtaDataSource;
        }
        return jndiName;
    }

}
