/*
 * Generated by XCodeGen v1.0
 * Sun Jul 07 16:05:42 EDT 2002
 */

package xcodegen.sample.domain.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import xcodegen.sample.domain.dto.OrderItemDTO;
    import xcodegen.sample.domain.dto.PersonDTO;
    import xcodegen.sample.domain.dao.PersonDAO;

/**
 * Item of an order
 *
 * @author Herve Tchepannou
 * @version 
 *
 * @see OrderItemDTO
 */
public class OrderItemDAO
{
    /** INSERT SQL statement */
    public static final String SQL_INSERT = "INSERT INTO ORDER_ITEM(id,description,unitPrice,quantity,orderId) VALUES(?,?,?,?,?)";
    
    /** SELECT SQL statement */
    public static final String SQL_SELECT = "SELECT ORDER_ITEM.id,ORDER_ITEM.description,ORDER_ITEM.unitPrice,ORDER_ITEM.quantity,ORDER_ITEM.orderId FROM ORDER_ITEM";
    
    /** UPDATE SQL statement */
    public static final String SQL_UPDATE = "UPDATE ORDER_ITEM SET description=?,unitPrice=?,quantity=?,orderId=?";
    
    /** Delete SQL Statement */
    public static final String SQL_DELETE = "DELETE FROM ORDER_ITEM";

    /** Active connection */
    private Connection cnn;
    
    
////////////////////////////////////
// Constructors
////////////////////////////////////

    public OrderItemDAO( Connection cnn )
    {
        if ( cnn == null )  throw new IllegalArgumentException( "cnn is null" );
        
        this.cnn = cnn;
    }
    

////////////////////////////////////
// Public methods
////////////////////////////////////
    
    /**
     * Persist a OrderItem into the database
     *
     * @param       OrderItem to persist
     * @return      value of the primary key of the object persisted
     * @throws      SQLException if any error occurs
     */
    public int create( OrderItemDTO data ) throws SQLException
    {
        PreparedStatement stmt = null;
        try
        {

            // Create the super-object
            PersonDAO superdao = new PersonDAO ( cnn );
            superdao.create( data );

            // Create the object
            stmt = cnn.prepareStatement( SQL_INSERT, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );
            
                            
        stmt.setInt( 1, data.getId() );
                                
        stmt.setString( 2, data.getDescription() );
                                
        stmt.setDouble( 3, data.getUnitPrice() );
                                
        stmt.setInt( 4, data.getQuantity() );
                                
        stmt.setInt( 5, data.getOrderId() );
                                
        stmt.setInt( 6, data.getId() );
    
            stmt.executeUpdate();
            
            return data.getId();
        }
        finally
        {
            if ( stmt != null )
            {
                try{    stmt.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
        }
    }

    /**
     * Persist modification on a OrderItem into the database
     *
     * @param       OrderItem to persist
     * @throws      SQLException if any error occurs
     */
    public void update( OrderItemDTO data ) throws SQLException
    {


        // Update the super-object
        PersonDAO superdao = new PersonDAO ( cnn );
        superdao.update( data );
        // Update the object
        PreparedStatement stmt = null;
        try
        {
            stmt = cnn.prepareStatement( SQL_UPDATE + " WHERE id=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );

                
                                
        stmt.setString( 1, data.getDescription() );
                
                                
        stmt.setDouble( 2, data.getUnitPrice() );
                
                                
        stmt.setInt( 3, data.getQuantity() );
                
                                
        stmt.setInt( 4, data.getOrderId() );
                                        
        stmt.setInt( 5, data.getId() );
    
            stmt.executeUpdate();
        }
        finally
        {
            if ( stmt != null )
            {
                try{    stmt.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
        }
    }


    /**
     * Remove a OrderItem from the database
     *
     * @param       pk  Primary key of the OrderItem to remove
     * @throws      SQLException if any error occurs
     */
    public void removeByPK( int pk ) throws SQLException
    {
        PreparedStatement stmt = null;
        try
        {

            // Remove the super-object
            PersonDAO superdao = new PersonDAO ( cnn );
            superdao.removeByPK( pk );
        }
        finally
        {
            if ( stmt != null )
            {
                try{    stmt.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
        }
    }



    /**
     * Find a OrderItem by its primary key
     *
     * @param pk    primary key of the OrderItem requested
     * @return      OrderItem found, <code>null</code> if nothing found
     * @throws      SQLException if any error occurs
     */
    public OrderItemDTO findByPK( int pk ) throws SQLException
    {
        ResultSet rs = null;
        PreparedStatement stmt = null;
        try
        {
            String sql = SQL_SELECT + " WHERE ORDER_ITEM.id=?";
            stmt = cnn.prepareStatement( sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );
                
                                
        stmt.setInt( 1, pk );
    
            rs = stmt.executeQuery();
            return rs.next() ? newDataObject( rs ) : null;
        }
        finally
        {
            if ( rs != null )
            {
                try{    rs.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
            if ( stmt != null )
            {
                try{    stmt.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
        }
    }

                                
    /**
     * Find all the items of a given order
     *
     * @param orderId     
     * @return                Collection of OrderItem, or an empty Collection if nothing found
     * @throws SQLException   if any error occurs
     */
     public Collection findByOrder ( int orderId ) throws SQLException
     {
        ResultSet rs = null;
        PreparedStatement stmt = null;
        try
        {
            String sql = SQL_SELECT + " WHERE orderId=?";
            stmt = cnn.prepareStatement( sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );


                                
        stmt.setInt( 1, orderId );
    
            rs = stmt.executeQuery();

            return filter( rs, 0, Integer.MAX_VALUE );
        }
        finally
        {
            if ( rs != null )
            {
                try{    rs.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
            if ( stmt != null )
            {
                try{    stmt.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
        }
     }


    /**
     * Find all the items of a given order.<p>
     * This function returns data page/page
     *
     * @param orderId     
     * @param _page           Index of the page to retrieve. 1st index is 1 (one)          
     * @param _pagesize       Max size of the page to retrieve
     * @return                Collection of OrderItem, or an empty Collection if nothing found
     * @throws SQLException   if any error occurs
     */
     public Collection findByOrder ( int orderId, int _page, int _pagesize ) throws SQLException
     {
        ResultSet rs = null;
        PreparedStatement stmt = null;
        try
        {
            String sql = SQL_SELECT + " WHERE orderId=?";
            stmt = cnn.prepareStatement( sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );


                                
        stmt.setInt( 1, orderId );
    
            rs = stmt.executeQuery();

            return filter( rs, (_page-1)*_pagesize, _pagesize );
        }
        finally
        {
            if ( rs != null )
            {
                try{    rs.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
            if ( stmt != null )
            {
                try{    stmt.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
        }
     }

  

//////////////////////////////////////////////////
// Private methods
//////////////////////////////////////////////////

    private Collection filter( ResultSet rs, int offset, int maxcount ) throws SQLException
    {
        Collection col = new ArrayList();
        for( int i=0, count=0 ; rs.next() && ( maxcount > count ) ; i++ )
        {
            if ( i >= offset )
            {
                col.add( newDataObject( rs ) );
                count++;
            }
        }
        return col;
    }

    private OrderItemDTO newDataObject( ResultSet rs ) throws SQLException
    {
        OrderItemDTO data = new OrderItemDTO();
        

                        data.setId( rs.getInt( 1 ) );

                        data.setDescription( rs.getString( 2 ) );

                        data.setUnitPrice( rs.getDouble( 3 ) );

                        data.setQuantity( rs.getInt( 4 ) );

                        data.setOrderId( rs.getInt( 5 ) );

        return data;
    }
}
