/** 
 * 
 * Copyright 2004 Hiram Chirino
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.codehaus.activemq.store.jdbc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.activemq.io.WireFormat;
import org.codehaus.activemq.io.impl.DefaultWireFormat;
import org.codehaus.activemq.service.impl.PersistenceAdapterSupport;
import org.codehaus.activemq.store.MessageStore;
import org.codehaus.activemq.store.PersistenceAdapter;
import org.codehaus.activemq.store.PreparedTransactionStore;
import org.codehaus.activemq.store.TopicMessageStore;
import org.codehaus.activemq.store.jdbc.adapter.DefaultJDBCAdapter;
import org.codehaus.activemq.util.FactoryFinder;
import org.codehaus.activemq.util.JMSExceptionHelper;

import javax.jms.JMSException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * A {@link PersistenceAdapter} implementation using JDBC for
 * persistence storage.
 *
 * @version $Revision: 1.4 $
 */
public class JDBCPersistenceAdapter extends PersistenceAdapterSupport {

    private static final Log log = LogFactory.getLog(JDBCPersistenceAdapter.class);
    private static FactoryFinder factoryFinder = new FactoryFinder("META-INF/services/org/codehaus/activemq/store/jdbc/");

    private WireFormat wireFormat = new DefaultWireFormat();
    private DataSource dataSource;
    private JDBCAdapter adapter;
	private String adapterClass;


    public JDBCPersistenceAdapter() {
    }

    public JDBCPersistenceAdapter(DataSource ds, WireFormat wireFormat) {
        this.dataSource = ds;
        this.wireFormat = wireFormat;
    }

    public Map getInitialDestinations() {
        return null;  /** TODO */
    }

    public MessageStore createQueueMessageStore(String destinationName) throws JMSException {
        if (adapter == null) {
            throw new IllegalStateException("Not started");
        }
        return new JDBCMessageStore(this, adapter, wireFormat.copy(), destinationName);
    }

    public TopicMessageStore createTopicMessageStore(String destinationName) throws JMSException {
        if (adapter == null) {
            throw new IllegalStateException("Not started");
        }
        return new JDBCTopicMessageStore(this, adapter, wireFormat.copy(), destinationName);
    }

    public PreparedTransactionStore createPreparedTransactionStore() throws JMSException {
        if (adapter == null) {
            throw new IllegalStateException("Not started");
        }
        return new JDBCPreparedTransactionStore(this, adapter, wireFormat.copy());
    }

    public void beginTransaction() throws JMSException {
        try {
            Connection c = dataSource.getConnection();
            c.setAutoCommit(false);
            TransactionContext.pushConnection(c);
        }
        catch (SQLException e) {
            throw JMSExceptionHelper.newJMSException("Failed to create transaction: " + e, e);
        }
    }

    public void commitTransaction() throws JMSException {
        Connection c = TransactionContext.popConnection();
        if (c == null) {
            log.warn("Commit while no transaction in progress");
        }
        else {
            try {
                c.commit();
            }
            catch (SQLException e) {
                throw JMSExceptionHelper.newJMSException("Failed to commit transaction: " + c + ": " + e, e);
            }
            finally {
                try {
                    c.close();
                }
                catch (Throwable e) {
                }
            }
        }
    }

    public void rollbackTransaction() {
        Connection c = TransactionContext.popConnection();
        try {
            c.rollback();
        }
        catch (SQLException e) {
            log.warn("Cannot rollback transaction due to: " + e, e);
        }
        finally {
            try {
                c.close();
            }
            catch (Throwable e) {
            }
        }
    }


    public void start() throws JMSException {
        beginTransaction();
        Connection c = null;
        try {
            // Load the right adapter for the database
            adapter = null;

            try {
            	c = getConnection();
            }
            catch (SQLException e) {
                throw JMSExceptionHelper.newJMSException("Could not get a database connection: "+e,e);                                 
            }

            // If the adapter class is not specified.. try to dectect they right type by getting
            // info from the database.
            if( adapterClass == null ) {
            	
                try {
		
                	// Make the filename file system safe.
	                String dirverName = c.getMetaData().getDriverName();
	                dirverName = dirverName.replaceAll("[^a-zA-Z0-9\\-]", "_");
	
	                log.debug("Database type: [" + dirverName + "]");
	                try {
		                adapter = (DefaultJDBCAdapter) factoryFinder.newInstance(dirverName);
	                }
	                catch (Throwable e) {
	                    log.warn("Unrecognized database type (" + dirverName + ").  Will use default JDBC implementation.");
	                    log.debug("Reason: " + e, e);
	                }
		                
	            }
	            catch (SQLException e) {
                    log.warn("JDBC error occured while trying to detect database type.  Will use default JDBC implementation: "+e.getMessage());
                    log.debug("Reason: " + e, e);                    
	            }
	            
            } else {
                try {
                	Class clazz = JDBCPersistenceAdapter.class.getClassLoader().loadClass(adapterClass);
                	adapter = (DefaultJDBCAdapter)clazz.newInstance();
                }
                catch (Throwable e) {
                    log.warn("Invalid JDBC adapter class class (" + adapterClass + ").  Will use default JDBC implementation.");
                    log.debug("Reason: " + e, e);
                }
            }
            
            // Use the default JDBC adapter if the 
            // Database type is not recognized.
            if (adapter == null) {
                adapter = new DefaultJDBCAdapter();
            }

            try {
                adapter.doCreateTables(c);
            }
            catch (SQLException e) {
                log.warn("Cannot create tables due to: " + e, e);
            }
            adapter.initSequenceGenerator(c);

        }
        finally {
            commitTransaction();
        }
    }


    public synchronized void stop() throws JMSException {
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public WireFormat getWireFormat() {
        return wireFormat;
    }

    public void setWireFormat(WireFormat wireFormat) {
        this.wireFormat = wireFormat;
    }

    public Connection getConnection() throws SQLException {
        Connection answer = TransactionContext.peekConnection();
        if (answer == null) {
            answer = dataSource.getConnection();
            answer.setAutoCommit(true);
        }
        return answer;
    }

    public void returnConnection(Connection connection) {
        if (connection == null) {
            return;
        }
        Connection peek = TransactionContext.peekConnection();
        if (peek != connection) {
            try {
                connection.close();
            }
            catch (SQLException e) {
            }
        }
    }
	
    /**
	 * @return Returns the adapterClass.
	 */
	public String getAdapterClass() {
		return adapterClass;
	}
	
	/**
	 * @param adapterClass The adapterClass to set.
	 */
	public void setAdapterClass(String adapterClass) {
		this.adapterClass = adapterClass;
	}
}
