/*
Copyright (C) 2000-2010  Ministere de la culture et de la communication (France), AJLSM
See LICENCE file
*/
package fr.gouv.culture.sdx.repository;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;

import fr.gouv.culture.sdx.exception.SDXException;
import fr.gouv.culture.sdx.exception.SDXExceptionCode;
import fr.gouv.culture.sdx.utils.configuration.ConfigurationUtils;
import fr.gouv.culture.sdx.utils.constants.Node;
import fr.gouv.culture.sdx.utils.save.SaveParameters;
import fr.gouv.culture.sdx.utils.save.Saveable;

public class ORACLERepository extends JDBCRepository {

    public void configure(Configuration configuration) throws ConfigurationException {
        // We will need the datasource _identifier here, so calling super
        super.configure(configuration);
        //well we need a good dsi value to work with so we verify it
        ConfigurationUtils.checkConfAttributeValue(ATTRIBUTE_DSI, this.dsi, configuration.getLocation());
    }

    /** Returns an SQL query that could create the table.
     * <p>
     * This query should not have any parameter.
     * @return The query.
     */

    protected String getTableCreationQuery() {
        // TODO: at some time, implement the proper handling of the original document (column data_t)
        //changed dataType of FIELD_DATA_TRANSFORMED from "LONGBLOB NOT NULL" TO  only "LONGBLOB"
        return "CREATE TABLE " + getTableName() + " ( " + FIELD_ID + " VARCHAR(255) NOT NULL, " + FIELD_DATA + " BLOB, PRIMARY KEY (" + FIELD_ID + "))";
    }

    /**
	 * @see fr.gouv.culture.sdx.utils.database.AbstractJDBCDatabase#getAllEntitiesWithLimitQuery(long, long)
	 * ORACLE implementation
	 * SELECT * FROM &gt;table_name&lt; LIMIT &gt;offset&lt;,&gt;number&lt; ;
	 */
	protected String getEntriesWithLimitQuery(long offset, long number) {
		String query = "SELECT * FROM " + getTableName();
		query += " LIMIT " + String.valueOf(offset) + "," + String.valueOf(number) + ";";
		return query;
	}

    /** Save the repository
	 * @see fr.gouv.culture.sdx.utils.save.Saveable#backup(fr.gouv.culture.sdx.utils.save.SaveParameters)
	 */
	public void backup(SaveParameters save_config) throws SDXException {
		super.backup(save_config);
		if(save_config != null)
			if(save_config.getAttributeAsBoolean(Saveable.ALL_SAVE_ATTRIB,false))
			{
				save_config.setAttribute(Node.Name.TYPE,"ORACLE");
			}
	}

    /**
     * Initialise l'entrepot. Si la table n'existe pas, elle est creee.
     * 
     * On surcharge cette methode car Oracle reagit bizarrement au
     * DatabaseMetaData. On fait simplement une requete.
     */
    public void init() throws SDXException {

        // La connexion et le resultset
        Connection conn = null;
        ResultSet rs = null;
        JDBCRepositoryConnection repoConn = (JDBCRepositoryConnection) getConnection();
        try {
            // On essaie de recuperer un enregistrement
            conn = repoConn.getConnection();
            Statement st = conn.createStatement();
            rs = st.executeQuery("SELECT " + FIELD_ID + ", " + FIELD_DATA + " FROM " + getTableName() + " WHERE " + FIELD_ID + " = '_____'");
        } 
        catch (SQLException e) {
            // S'il y a exception, c'est probablement parce que la table n'existe pas
            // On va la creer, si ce n'etait pas le probleme alors tant pis
            createTable(conn);
        }
        finally {
            // On detruit nos objets de connexion
            if (rs != null) {
                try {
                    rs.close();
                }
                catch (SQLException e) {
                    String[] args = new String[2];
                    args[0] = getId();
                    args[1] = e.getMessage();
                    throw new SDXException(super.getLog(), SDXExceptionCode.ERROR_CLOSE_RESULT_SET, args, e);
                }
            }
            if ( repoConn != null ) {
                repoConn.commit();
                releaseConnection(repoConn);
            }
        }
    }

    /** Restore the repository
	 * @see fr.gouv.culture.sdx.utils.save.Saveable#restore(fr.gouv.culture.sdx.utils.save.SaveParameters)
	 */
	public void restore(SaveParameters save_config) throws SDXException {
		super.restore(save_config);
	}

}
