package com.dragonsoft.tryapp.ejb.entity;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.ejb.EJBException;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;

import com.dragonsoft.tryapp.common.CourseObj;
import com.dragonsoft.tryapp.ejb.entity.interfaces.CoursePK;

/**
 * @author Shaun Newsum
 * 
 * The CourseBean handles calls to create/update/delete and query for courses
 * from within the database.
 * 
 * The bean can be used to represent a single entity or used as a utility object
 * to query for collections of courses
 * 
 * @ejb.bean name = "Course" display-name = "Course EJB" description = "EJB to
 *           create/update/delete and query for courses" 
 * 			 view-type = "both"
 * 			type="BMP"
 *           jndi-name = "ejb/Course"
 * 			 primkey-field="itemKey"
 * 			 
 */
public class CourseBean extends ConnectionBean {
	
	private CoursePK itemKey;
	
	private CourseObj course;
	
	private EntityContext ctx;
	
	/**
	 * Constructor.
	 */
	public CourseBean() {
		super();
	}

	// -- Getter/Setters
	/**
	 * Business method
	 * 
	 * @ejb.interface-method view-type = "both"
	 */
	public CourseObj getCourse() {
		return course;
	}
	
	/**
	 * Business method
	 * 
	 * @ejb.interface-method view-type = "both"
	 */
	public void setCourse(CourseObj course) {
		this.course = course;
	}
	
	/**
	 * Business method
	 * 
	 * @ejb.interface-method view-type = "both"
	 */
	public CoursePK getItemKey() {
		return itemKey;
	}
	/**
	 * Business method
	 * 
	 * @ejb.interface-method view-type = "both"
	 */
	public void setItemKey(CoursePK itemKey) {
		this.itemKey = itemKey;
	}
	//	 -- EJB Methods
	public void ejbActivate() throws EJBException, RemoteException {
	}

	public void ejbPassivate() throws EJBException, RemoteException {
	}

	public void setEntityContext(EntityContext arg0) throws EJBException,
			RemoteException {
		this.ctx = arg0;
	}

	public void unsetEntityContext() throws EJBException, RemoteException {
		this.ctx = null;
	}
	
	/**
	 * Inserts a new Course into the database.
	 * 
	 * @throws EJBException
	 * @throws RemoteException
	 * @ejb.create-method
	 */
	public CoursePK ejbCreate(CourseObj course) throws javax.ejb.CreateException{
		String id = course.getCourseID();
		String num = course.getCourseNumber();
		String sec = (String) course.getCourseSections().toArray()[0];
		String term = course.getCourseTerm();
		String name = course.getCourseName();
				
		try {
			Connection connection = getConnection();
			PreparedStatement statement = 
				connection.prepareStatement("INSERT INTO course (courseID, courseNum, sectionNum, quarterNum, name) VALUES (?, ?, ?, ?, ?)"); 
											
			statement.setString(1, id);
			statement.setString(2, num);
			statement.setString(3, sec);
			statement.setString(4, term);
			statement.setString(5, name);
			ResultSet resultSet = statement.executeQuery();
			if (!resultSet.next()) {
				statement.close();
				connection.close();
				throw new EJBException("Could not create Course.");
			}
			statement.close();
			connection.close();
		} catch (SQLException e) {
			throw new EJBException("Could not create Course");
		}	
		
		return new CoursePK(id);
	}

	public void ejbPostCreate(CourseObj course) throws EJBException, RemoteException {}
	
	/**
	 * Loads the course from the underlying database.
	 *  
	 */
	public void ejbLoad() throws EJBException, RemoteException {
		CoursePK key = (CoursePK) ctx.getPrimaryKey();
		Connection connection = null;
		try {
			connection = getConnection();
			PreparedStatement statement = 
				connection.prepareStatement("SELECT courseID, courseNum, sectionNum, quarterNum, name FROM course " +
											"WHERE courseID=?");
			statement.setString(1, key.getCourseID());
			ResultSet resultSet = statement.executeQuery();
			if (!resultSet.next()) {
				statement.close();
				connection.close();
				throw new EJBException("Course not found: id = " + key.getCourseID());
			}
			
			ArrayList sections = new ArrayList();
			sections.add(resultSet.getString(3));
			course = new CourseObj(resultSet.getString(1),
								resultSet.getString(5),
								resultSet.getString(2),
								sections,
								resultSet.getString(4));
			this.itemKey = key;
			statement.close();
			connection.close();
		} catch (SQLException e) {
			
			throw new EJBException("Could not load Course: id = " + key.getCourseID(),e);
		}
		finally{
			try {
				connection.close();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	/**
	 * Deletes the Course from the underlying database.
	 */
	public void ejbRemove() throws RemoveException, EJBException,
			RemoteException {

		CoursePK key = (CoursePK) ctx.getPrimaryKey();
		try {
			Connection connection = getConnection();
			PreparedStatement statement = connection
					.prepareStatement("DELETE FROM course WHERE courseID = ?");
			statement.setString(1, key.getCourseID());
			if (statement.executeUpdate() != 1) {
				throw new RemoveException("Could not remove Course: id = "
						+ key.getCourseID());
			}
			statement.close();
			connection.close();
		} catch (SQLException e) {
			throw new EJBException("Could not remove Course: id = " + key.getCourseID());
		}

	}

	/**
	 * Stores the Course to the underlying database.
	 *  
	 */
	public void ejbStore() throws EJBException, RemoteException {}
	
	/**
	 * Finds all Course.
	 * 
	 * @return a collection of Course
	 * @throws FinderException
	 *  
	 */
	public CoursePK ejbFindByPrimaryKey(CoursePK courseID) throws FinderException {
			Connection connection = null;
			PreparedStatement statement = null;
			ResultSet resultSet = null;
			try {
				connection = getConnection();
				statement = connection.prepareStatement("SELECT * FROM course WHERE courseID = ?");
				statement.setString(1, courseID.getCourseID());
				resultSet = statement.executeQuery();
				if (!resultSet.next()) {
					throw new FinderException("Could not find by PrimaryKey:"
						+ courseID.getCourseID());
				} 
				resultSet.close();
				statement.close();
				
			} catch (SQLException e) {
				throw new EJBException("Could not find Course: id = " + courseID.getCourseID());
			}
			finally{
				try {
					connection.close();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		return courseID;
	}
	
} // CourseBean
