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 javax.ejb.EJBException;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;

import com.dragonsoft.tryapp.common.User;
import com.dragonsoft.tryapp.ejb.entity.interfaces.UserRolePK;

/**
 * @author Shaun Newsum
 * 
 * The StudentBean handles calls to create/update/delete and query for
 * students 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 students
 *  
 * @ejb.bean	name = "Student"
 * 				display-name = "Student EJB"
 * 				description = "EJB to create/update/delete and query for students"
 * 				view-type = "both"
 * 				type="BMP"
 * 				jndi-name = "ejb/Student"
 * 				primkey-field="itemKey"
 * 				
 */
public class StudentBean extends ConnectionBean {

	private UserRolePK itemKey;
	
	private EntityContext ctx;
	
	/**
	 * Constructor.
	 */
	public StudentBean() {
		super();
	}
	
	
	/**
	 * Business method
	 * @ejb.interface-method  view-type = "both"
	 */
	public UserRolePK getItemKey() {
		return itemKey;
	}
	/**
	 * Business method
	 * @ejb.interface-method  view-type = "both"
	 */
	public void setItemKey(UserRolePK 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 {
		ctx = null;
	}

	/**
	 * Inserts a new Instructor into the database.
	 * @throws EJBException
	 * @throws RemoteException
	 * @ejb.create-method 
	 */
	public UserRolePK ejbCreate(String username, String courseID) throws javax.ejb.CreateException {
		try {
			Connection connection = getConnection();
			PreparedStatement statement = 
				connection.prepareStatement("INSERT INTO student (courseID, username) VALUES (?, ?)"); 
			statement.setString(1, courseID);
			statement.setString(2, username);
			statement.executeUpdate();
			statement.close();
			connection.close();						
		} catch (SQLException e) {
			throw new EJBException("Could not create Student");
		}	
		
		return new UserRolePK(courseID, username);
	}
	
	public void ejbPostCreate(String username, String courseID) throws EJBException, RemoteException {}
	
	/**
	 * Loads the user from the underlying database.
	 */
	public void ejbLoad() throws EJBException, RemoteException {}

	/**
	 * Deletes the user from the underlying database.  
	 */
	public void ejbRemove() throws RemoveException, EJBException,
			RemoteException {
		UserRolePK key = (UserRolePK)ctx.getPrimaryKey();
		try {
			Connection connection = getConnection();
			PreparedStatement statement = connection
					.prepareStatement("DELETE FROM student WHERE courseID = ? AND username = ?");
			statement.setString(1, key.getCourseID());
			statement.setString(1, key.getUsername());
			if (statement.executeUpdate() != 1) {
				throw new RemoveException("Could not remove Student: username = "
						+ key.getUsername() + " courseID = " + key.getCourseID());
			}
			statement.close();
			connection.close();
		} catch (SQLException e) {
			throw new EJBException("Could not remove Student: username = "
					+ key.getUsername() + " courseID = " + key.getCourseID());
		}

	}

	/**
	 * Stores the user to the underlying database.
	 */
	public void ejbStore() throws EJBException, RemoteException {}
	
	// -- Utility Methods
	
	/**
	 * Business method
	 * @ejb.finder   view-type = "both"
	 * 				 result-type-mapping = "Remote"
	 */
	public UserRolePK ejbFindByPrimaryKey(UserRolePK key)
		throws FinderException {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			ResultSet set = null;
			connection = getConnection();
			statement = connection.prepareStatement("SELECT username, courseID FROM student WHERE courseID =  ?");
			statement.setString(1, key.getUsername());
			statement.setString(2, key.getCourseID());
			resultSet = statement.executeQuery();
			if (!set.next()) {
				throw new FinderException("Could not find by PrimaryKey:"
					+ key.getCourseID() + " : " + key.getUsername());
			}
			resultSet.close();
			statement.close();
		} catch (SQLException e) {
			throw new EJBException("Could not find Student: id = " + key.getUsername());
		}
		
		return key;
		
	}
	
	/**
	 * Finds all users.
	 * @return a collection of User objects
	 * @throws FinderException
	 * 
	 */
	public Collection ejbFindAllByCourseID(String courseID) throws FinderException {
		try {
			  Connection connection = getConnection();
			  PreparedStatement statement = connection.prepareStatement("SELECT username, courseID FROM Student WHERE courseID =  ?");
			  statement.setString(1, courseID);
			  ResultSet resultSet = statement.executeQuery();
			  if (!resultSet.next()) {
				statement.close();
				connection.close();
				throw new FinderException("Could not find any Studnets");
			  }
			  
			  ArrayList itemList = new ArrayList();
			  
			  User temp = new User(resultSet.getString(1),resultSet.getString(2), 0);
			  itemList.add(temp);
			  while (resultSet.next()) {
			  	temp = new User(resultSet.getString(1),resultSet.getString(2), 0);
			  	itemList.add(temp);
			  }
			  statement.close();
			  connection.close();
			  return itemList;
		} catch (SQLException e) {
			throw new EJBException("Could not find any Students.");
		}
	}
	
} // StudentBean
