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 java.util.Collection;
import java.util.List;

import javax.ejb.EJBException;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;

import com.dragonsoft.tryapp.common.AssignmentObj;
import com.dragonsoft.tryapp.ejb.entity.interfaces.AssignmentPK;

/**
 * @author Shaun Newsum
 * 
 * The AssignmentBean handles calls to create/update/delete and query for
 * assignments 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 assignments
 *  
 *  @ejb.bean	name = "Assignment"
 * 				display-name = "Assignment EJB"
 * 				description = "EJB to create/update/delete and query for assignments"
 *	            jndi-name="ejb/Assignment"
 *  	    	type="BMP"
 *      	    view-type="both"
 *  			primkey-field = "itemKey"
 * 			
 */
public class AssignmentBean extends ConnectionBean {

	private AssignmentPK itemKey;

	private AssignmentObj assignment;

	private EntityContext ctx;

	/**
	 * Constructor.
	 */
	public AssignmentBean() {
		super();
	}

	// -- Getter/Setters
	/**
	 * Business method
	 * @ejb.interface-method  view-type = "both"
	 */
	public AssignmentObj getAssignment() {
		return assignment;
	}

	/**
	 * Business method
	 * @ejb.interface-method  view-type = "both"
	 */
	public void setAssignment(AssignmentObj assignment) {
		this.assignment = assignment;
	}

	/**
	 * Business method
	 * 
	 * @ejb.interface-method view-type = "both"
	 */
	public AssignmentPK getItemKey() {
		return itemKey;
	}
	/**
	 * Business method
	 * 
	 * @ejb.interface-method view-type = "both"
	 */
	public void setItemKey(AssignmentPK 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 {
		ctx = arg0;
	}

	public void unsetEntityContext() throws EJBException, RemoteException {
		ctx = null;
	}

	/**
	 * Inserts a new Assignment into the database.
	 * @throws EJBException
	 * @throws RemoteException
	 * @ejb.create-method 
	 */
	public AssignmentPK ejbCreate(AssignmentObj assignment)
		throws javax.ejb.CreateException{
		String assignmentID = assignment.getAssignmentID();
		String name = assignment.getAssignmentName();
		try {
			Connection connection = getConnection();
			PreparedStatement statement = connection
				.prepareStatement("INSERT INTO assignment (name) VALUES (?); "
					+ "SELECT assignmentID, name FROM assignment WHERE assignmentID = LAST_INSERT_ID(); ");
			statement.setString(1, name);
			
			ResultSet resultSet = statement.executeQuery();
			if (!resultSet.next()) {
				statement.close();
				connection.close();
				throw new EJBException("Could not create Assignment");
			}
			assignment = new AssignmentObj(resultSet.getString(1), resultSet
				.getString(2), null, null, null);

			statement.close();
			connection.close();
			return new AssignmentPK(assignment.getAssignmentID());
		} catch (SQLException e) {
			throw new EJBException("Could not create Assignment");
		}
	}
	
	public void ejbPostCreate(AssignmentObj assignment)
		throws EJBException,
		RemoteException {}
	
	/**
	 * Loads the assignment from the underlying database.
	 * 
	 */
	public void ejbLoad() throws EJBException, RemoteException {
		AssignmentPK key = (AssignmentPK) ctx.getPrimaryKey();
		try {
			Connection connection = getConnection();
			PreparedStatement statement = connection
				.prepareStatement("SELECT assignmentID, name "
					+ "FROM assignment WHERE assignmentID = ?");
			statement.setString(1, key.getAssignmentID());
			ResultSet resultSet = statement.executeQuery();
			if (!resultSet.next()) {
				statement.close();
				connection.close();
				throw new EJBException("Assignment not found: id = "
					+ key.getAssignmentID());
			}

			assignment = new AssignmentObj(resultSet.getString(1), resultSet
				.getString(2), null, null, null);
			statement.close();
			connection.close();
		} catch (SQLException e) {
		
			throw new EJBException("Could not load Assignment: id = "
				+ key.getAssignmentID(),e);
		}
	}

	/**
	 * Deletes the assignment from the underlying database.  
	 */
	public void ejbRemove()
		throws RemoveException,
		EJBException,
		RemoteException {

		AssignmentPK key = (AssignmentPK) ctx.getPrimaryKey();
		try {
			Connection connection = getConnection();
			PreparedStatement statement = connection
				.prepareStatement("DELETE FROM assignment WHERE assignmentID = ?");
			statement.setString(1, key.getAssignmentID());
			if (statement.executeUpdate() != 1) {
				throw new RemoveException("Could not remove Assignment: id = "
					+ key.getAssignmentID());
			}
			statement.close();
			connection.close();
			itemKey = null;
			assignment = null;
		} catch (SQLException e) {
			throw new EJBException("Could not remove Assignment: id = "
				+ key.getAssignmentID());
		}

	}

	/**
	 * Stores the assignment to the underlying database.
	 * 
	 */
	public void ejbStore() throws EJBException, RemoteException {
		String id = assignment.getAssignmentID();
		String name = assignment.getAssignmentName();
		AssignmentPK key = (AssignmentPK) ctx.getPrimaryKey();
		try {
			Connection connection = getConnection();
			PreparedStatement statement = connection
				.prepareStatement("UPDATE assignment SET name = ? WHERE assignmentID = ?");
			statement.setString(1, name);
			statement.setString(2, key.getAssignmentID());
			statement.executeUpdate();
			statement.close();
			connection.close();
		} catch (SQLException e) {
			throw new EJBException("Could not store Assignment: id = "
				+ key.getAssignmentID());
		}

	}

	// -- Utility Methods
	/**
	 * Business method
	 * @ejb.finder   view-type = "both"
	 * 				 result-type-mapping = "Remote"
	 */
	public AssignmentPK ejbFindByPrimaryKey(AssignmentPK assignmentID)
		throws FinderException {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			ResultSet set = null;
			connection = getConnection();
			statement = connection
				.prepareStatement("SELECT assignmentID, name FROM assignment WHERE assignmentID = ?");
			statement.setString(1, assignmentID.getAssignmentID());
			resultSet = statement.executeQuery();
			if (!set.next()) {
				throw new FinderException("Could not find by PrimaryKey:"
					+ assignmentID);
			}
			resultSet.close();
			statement.close();

		} catch (SQLException e) {
			throw new EJBException("Could not find Assignment: id = "
				+ assignmentID.getAssignmentID());
		}

		return assignmentID;
	}

	/**
	 * Finds all assignments related to the specified course.
	 * @param courseID
	 * @return a collection of Assignments
	 * @throws FinderException
	 * 
	 */
	public Collection ejbFindByAllByCourseID(String courseID)
		throws FinderException {
		Connection connection = null;
		List itemList = new ArrayList();
		try {
			connection = getConnection();
			PreparedStatement statement = connection
				.prepareStatement("SELECT DISTINCT t1.assignmentID "
					+ "From assignment as t1, "
					+ "submissionroster as t2 WHERE t1.assignmentID = "
					+ "t2.assignmentID AND t2.courseID = ?");
			statement.setString(1, courseID);
			ResultSet resultSet = statement.executeQuery();
			if (!resultSet.next()) {
				statement.close();
				connection.close();
				throw new FinderException("Could not find any Assignments");
			}
			
			AssignmentPK temp = new AssignmentPK(resultSet.getString(1)); 
			
			itemList.add(temp);
			while (resultSet.next()) {
				temp = new AssignmentPK(resultSet.getString(1));
			
				itemList.add(temp);
			}

			statement.close();
			connection.close();
		} catch (SQLException e) {
			throw new EJBException("Could not find any Assignments.");
		}
		finally{
			try {
				connection.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		return itemList;
	}

	
} // AssignmentBean
