/*
 * 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.OrderDTO;
    import xcodegen.sample.domain.dto.PersonDTO;
    import xcodegen.sample.domain.dao.PersonDAO;

/**
 * Order made by a user
 *
 * @author Herve Tchepannou
 * @version 
 *
 * @see OrderDTO
 */
public class OrderDAO
{
    /** INSERT SQL statement */
    public static final String SQL_INSERT = "INSERT INTO ORDER(id,created,personId) VALUES(?,?,?)";
    
    /** SELECT SQL statement */
    public static final String SQL_SELECT = "SELECT ORDER.id,ORDER.created,ORDER.personId FROM ORDER";
    
    /** UPDATE SQL statement */
    public static final String SQL_UPDATE = "UPDATE ORDER SET created=?,personId=?";
    
    /** Delete SQL Statement */
    public static final String SQL_DELETE = "DELETE FROM ORDER";

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

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

////////////////////////////////////
// Public methods
////////////////////////////////////
    
    /**
     * Persist a Order into the database
     *
     * @param       Order to persist
     * @return      value of the primary key of the object persisted
     * @throws      SQLException if any error occurs
     */
    public int create( OrderDTO 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() );
                            
        java.util.Date value2 = data.getCreated();
                    stmt.setTimestamp( 2, value2 != null ? new java.sql.Timestamp( value2.getTime() ) : null ); 
                                        
        stmt.setInt( 3, data.getPersonId() );
                                
        stmt.setInt( 4, data.getId() );
    
            stmt.executeUpdate();
            
            return data.getId();
        }
        finally
        {
            if ( stmt != null )
            {
                try{    stmt.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
        }
    }

    /**
     * Persist modification on a Order into the database
     *
     * @param       Order to persist
     * @throws      SQLException if any error occurs
     */
    public void update( OrderDTO 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 );

                
                            
        java.util.Date value1 = data.getCreated();
                    stmt.setTimestamp( 1, value1 != null ? new java.sql.Timestamp( value1.getTime() ) : null ); 
                        
                                
        stmt.setInt( 2, data.getPersonId() );
                                        
        stmt.setInt( 3, data.getId() );
    
            stmt.executeUpdate();
        }
        finally
        {
            if ( stmt != null )
            {
                try{    stmt.close();   } catch( Exception e )  { e.printStackTrace(); }
            }
        }
    }


    /**
     * Remove a Order from the database
     *
     * @param       pk  Primary key of the Order 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 Order by its primary key
     *
     * @param pk    primary key of the Order requested
     * @return      Order found, <code>null</code> if nothing found
     * @throws      SQLException if any error occurs
     */
    public OrderDTO findByPK( int pk ) throws SQLException
    {
        ResultSet rs = null;
        PreparedStatement stmt = null;
        try
        {
            String sql = SQL_SELECT + " WHERE ORDER.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 orders of a Person at a given period
     *
     * @param email     
     * @param startDate     
     * @param endDate     
     * @return                Collection of Order, or an empty Collection if nothing found
     * @throws SQLException   if any error occurs
     */
     public Collection findByPerson_Date ( String email, java.util.Date startDate, java.util.Date endDate ) throws SQLException
     {
        ResultSet rs = null;
        PreparedStatement stmt = null;
        try
        {
            String sql = SQL_SELECT + " INNER JOIN Person ON ORDER.personId=PERSON.id WHERE email=? AND created BETWEEN ? AND ?";
            stmt = cnn.prepareStatement( sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );


                                
        stmt.setString( 1, email );
    
                            
        java.util.Date value2 = startDate;
                    stmt.setTimestamp( 2, value2 != null ? new java.sql.Timestamp( value2.getTime() ) : null ); 
            
                            
        java.util.Date value3 = endDate;
                    stmt.setTimestamp( 3, value3 != null ? new java.sql.Timestamp( value3.getTime() ) : null ); 
            
            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 orders of a Person at a given period.<p>
     * This function returns data page/page
     *
     * @param email     
     * @param startDate     
     * @param endDate     
     * @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 Order, or an empty Collection if nothing found
     * @throws SQLException   if any error occurs
     */
     public Collection findByPerson_Date ( String email, java.util.Date startDate, java.util.Date endDate, int _page, int _pagesize ) throws SQLException
     {
        ResultSet rs = null;
        PreparedStatement stmt = null;
        try
        {
            String sql = SQL_SELECT + " INNER JOIN Person ON ORDER.personId=PERSON.id WHERE email=? AND created BETWEEN ? AND ?";
            stmt = cnn.prepareStatement( sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );


                                
        stmt.setString( 1, email );
    
                            
        java.util.Date value2 = startDate;
                    stmt.setTimestamp( 2, value2 != null ? new java.sql.Timestamp( value2.getTime() ) : null ); 
            
                            
        java.util.Date value3 = endDate;
                    stmt.setTimestamp( 3, value3 != null ? new java.sql.Timestamp( value3.getTime() ) : null ); 
            
            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 OrderDTO newDataObject( ResultSet rs ) throws SQLException
    {
        OrderDTO data = new OrderDTO();
        

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

                        data.setCreated( rs.getTimestamp( 2 ) );

                        data.setPersonId( rs.getInt( 3 ) );

        return data;
    }
}
