package org.apache.ojb.broker.util.sequence;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache ObjectRelationalBridge" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache ObjectRelationalBridge", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

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

import org.apache.ojb.broker.PersistenceBroker;
import org.apache.ojb.broker.PersistenceBrokerException;
import org.apache.ojb.broker.PersistenceBrokerSQLException;
import org.apache.ojb.broker.metadata.ClassDescriptor;
import org.apache.ojb.broker.query.Query;
//import org.apache.ojb.broker.singlevm.PersistenceBrokerImpl;
import org.apache.ojb.broker.util.logging.LoggerFactory;

/**
 * A SapDB SequenceManager that uses Sequences from database.
 * This class is responsible for creating new unique ID's for primary columns
 * containing integer values.
 * The SequenceManager is aware of extends, that is: if you ask for an uid for an Interface with several implementor classes,
 * or a baseclass with several subclasses the returned uid will unique accross all tables representing
 * objects of the extent in question.
 * This code is based on SequenceManagerDefaultImpl from thma.
 *
 * @author: Edson Carlos Ericksson Richter
 * @version $Id: $
 */
public class SequenceManagerSapImpl implements SequenceManager
{

    /**
     * reference to the PersistenceBroker
     */
    protected PersistenceBroker broker;

    /**
     * singleton instance of the SequenceManager
     */
    private static SequenceManagerSapImpl _instance;

    /**
     *
     * Public constructor
     *
     */
    public SequenceManagerSapImpl(PersistenceBroker broker)
    {
        this.broker = broker;
    }
    
    private String _getTable( String fullTableName ) {
      int i = fullTableName.lastIndexOf( "." ) + 1;
      
      return fullTableName.substring( i );
    }

    /**
     * Returns next Id get from "sequence sequence.NextVal from Dual".
     * Mount sequence name as:
     * Schema.SQ_tableName_fieldName. If you have a table named MY_TABLE
     * and the sequenced field is MY_FIELD on schema MY_SCHEMA, the command
     * to create the sequence is:
     * CREATE SEQUENCE MY_SCHEMA.SQ_MY_TABLE_MY_FIELD
     */
    private synchronized int getNextId(Class clazz, String fieldName) throws PersistenceBrokerException
    {
        int result = 0;
        ResultSet rs = null;
        Statement stmt = null;
        try
        {
          ClassDescriptor cld = broker.getClassDescriptor( clazz );
          
          String prefix = cld.getSchema( );
          String table = _getTable( cld.getFullTableName() );
          String column = cld.getFieldDescriptorByName(fieldName).getColumnName();
          StringBuffer sql = new StringBuffer( "SELECT " );

          if( prefix != null )
            sql.append( prefix ).append( "." );

          sql.append( "SQ_" );
          sql.append( table ).append( "_" ).append( column );
          sql.append( ".NextVal from DUAL" );
          stmt = broker.getStatementManager().getGenericStatement(cld, Query.NOT_SCROLLABLE);
          rs = stmt.executeQuery(sql.toString( ));
          rs.next();
          result = rs.getInt(1);
        }
        catch (Throwable t)
        {
            LoggerFactory.getDefaultLogger().error(t);
            throw new PersistenceBrokerException(t);
        }
        finally
        {
            try
            {
                if (rs != null)
                    rs.close();
                if (stmt != null)
                   stmt.close();
            }
            catch (SQLException e)
            {
                LoggerFactory.getDefaultLogger().error(e);
                throw new PersistenceBrokerSQLException(e);
            }
            return result;
        }
    }

    /**
     * returns a unique int for class clazz and field fieldName.
     * the returned uid is unique accross all tables in the extent of clazz.
     */
    public int getUniqueId(Class clazz, String fieldName)
    {
        return getNextId(clazz, fieldName);
    }

    /**
     * returns a unique String for class clazz and field fieldName.
     * the returned uid is unique accross all tables in the extent of clazz.
     *
     */
    public String getUniqueString(Class clazz, String fieldName)
    {
        return Integer.toString(getUniqueId(clazz, fieldName));
    }

    /**
     * returns a unique long value for class clazz and field fieldName.
     * the returned number is unique accross all tables in the extent of clazz.
     */
    public long getUniqueLong(Class clazz, String fieldName)
    {
        return (long) getUniqueId(clazz, fieldName);
    }

    /**
     * returns a unique Object for class clazz and field fieldName.
     * the returned Object is unique accross all tables in the extent of clazz.
     */
    public Object getUniqueObject(Class clazz, String fieldName)
    {
        return getUniqueString(clazz, fieldName);
    }
}


