/*
 * Copyright 2002-2008 the original author or authors.
 *
 * 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.springframework.samples.petclinic.config;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * A factory that creates a data source fit for use in a system test environment. Creates a simple data source that
 * connects to an in-memory database pre-loaded with data.
 *
 * This factory returns a fully-initialized DataSource implementation. When the DataSource is returned, callers are
 * guaranteed that the database schema and data will have been loaded by that time.
 *
 * Is a FactoryBean, for exposing the fully-initialized DataSource as a Spring bean. See {@link #getObject()}.
 */
class EmbeddedDataSourceFactory implements FactoryBean {

    private static Log logger = LogFactory.getLog(EmbeddedDataSourceFactory.class);

    // configurable properties

    private String databaseName;

    private Resource schemaLocation;

    private Resource dataLocation;

    /**
     * The object created by this factory.
     */
    private DataSource dataSource;

    /**
     * Sets the name of the database to create.
     * @param testDatabaseName the name of the database, i.e. "petclinic"
     */
    public void setDatabaseName(String testDatabaseName) {
        this.databaseName = testDatabaseName;
    }

    /**
     * Sets the location of the file containing the schema DDL to export to the database.
     * @param schemaLocation the location of the database schema DDL
     */
    public void setSchemaLocation(Resource schemaLocation) {
        this.schemaLocation = schemaLocation;
    }

    /**
     * Sets the location of the file containing the data to load into the database.
     * @param testDataLocation the location of the data file
     */
    public void setDataLocation(Resource testDataLocation) {
        this.dataLocation = testDataLocation;
    }

    // implementing FactoryBean

    // this method is called by Spring to expose the DataSource as a bean
    public Object getObject() throws Exception {
        if (dataSource == null) {
            initDataSource();
        }
        return dataSource;
    }

    public Class<?> getObjectType() {
        return DataSource.class;
    }

    public boolean isSingleton() {
        return true;
    }

    // internal helper methods

    // encapsulates the steps involved in initializing the data source: creating it, and populating it
    private void initDataSource() {
        // create the in-memory database source first
        this.dataSource = createDataSource();
        if (logger.isDebugEnabled()) {
            logger.debug("Created in-memory database '" + databaseName + "'");
        }
        // now populate the database by loading the schema and data
        populateDataSource();
        if (logger.isDebugEnabled()) {
            logger.debug("Exported schema in " + schemaLocation);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded data in " + dataLocation);
        }
    }

    private DataSource createDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        // use the HsqlDB JDBC driver
        dataSource.setDriverClassName(org.hsqldb.jdbcDriver.class.getName());
        // have it create an in-memory database
        dataSource.setUrl("jdbc:hsqldb:mem:" + databaseName);
        dataSource.setUsername("sa");
        dataSource.setPassword("");
        return dataSource;
    }

    private void populateDataSource() {
        DatabasePopulator populator = new DatabasePopulator(dataSource);
        populator.populate();
    }

    /**
     * Populates a in memory data source with data.
     */
    private class DatabasePopulator {

        private DataSource dataSource;

        /**
         * Creates a new database populator.
         * @param dataSource the data source that will be populated.
         */
        public DatabasePopulator(DataSource dataSource) {
            this.dataSource = dataSource;
        }

        /**
         * Populate the database by creating the database schema from 'schema.sql' and inserting the data in
         * 'testdata.sql'.
         */
        public void populate() {
            Connection connection = null;
            try {
                connection = dataSource.getConnection();
                createDatabaseSchema(connection);
                insertTestData(connection);
            } catch (SQLException e) {
                throw new RuntimeException("SQL exception occurred acquiring connection", e);
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                    }
                }
            }
        }

        // create the application's database schema (tables, indexes, etc.)
        private void createDatabaseSchema(Connection connection) {
            try {
                String sql = parseSqlIn(schemaLocation);
                executeSql(sql, connection);
            } catch (IOException e) {
                throw new RuntimeException("I/O exception occurred accessing the database schema file", e);
            } catch (SQLException e) {
                throw new RuntimeException("SQL exception occurred exporting database schema", e);
            }
        }

        // populate the tables with data
        private void insertTestData(Connection connection) {
            try {
                String sql = parseSqlIn(dataLocation);
                executeSql(sql, connection);
            } catch (IOException e) {
                throw new RuntimeException("I/O exception occurred accessing the data file", e);
            } catch (SQLException e) {
                throw new RuntimeException("SQL exception occurred loading data", e);
            }
        }

        // utility method to read a .sql txt input stream
        private String parseSqlIn(Resource resource) throws IOException {
            InputStream is = null;
            try {
                is = resource.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                StringWriter sw = new StringWriter();
                BufferedWriter writer = new BufferedWriter(sw);

                for (int c=reader.read(); c != -1; c=reader.read()) {
                    writer.write(c);
                }
                writer.flush();
                return sw.toString();

            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }

        // utility method to run the parsed sql
        private void executeSql(String sql, Connection connection) throws SQLException {
            Statement statement = connection.createStatement();
            statement.execute(sql);
        }
    }

}
