/*
 * Created on Apr 19, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.dragonsoft.tryapp.ejb.entity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;

import com.dragonsoft.tryapp.common.exceptions.ExceptionHandler;
import com.dragonsoft.tryapp.common.exceptions.TryException;
import com.dragonsoft.tryapp.ejb.entity.interfaces.AssignmentKey;
import com.dragonsoft.tryapp.ejb.entity.interfaces.CourseKey;
import com.dragonsoft.tryapp.ejb.entity.utils.AssignmentFSUtils;
import com.dragonsoft.tryapp.ejb.entity.utils.CourseFSUtils;
import com.dragonsoft.tryapp.ejb.entity.utils.FileSystemTraverser;
import com.dragonsoft.tryapp.support.TryFileSystem;

/**
 * @author Greg
 * This bean is responsible for the creation and persistance of 
 * files associated with the skeleton model of an Assignment.
 * 
 * @ejb.bean name="AssignmentFS"
 *           display-name="Name for AssignmentFS"
 *           description="Description for AssignmentFS"
 *           jndi-name="ejb/AssignmentFS"
 *           type="BMP"
 *           view-type="both"
 * 			 primkey-field="key"
 */
public class AssignmentFSBean implements EntityBean {

	public static final String DESCRIPTION_FILENAME = "description.fire";
	public static final String ACTIVITY_DIRECTORY = "activities";
	public static final String COURSE_FILENAME = "course.fire";

	private EntityContext ctx;

	private String name;
	private String assignmentNumber;
	private CourseKey course;
	private AssignmentKey key;

	/**
	 * 
	 */
	public AssignmentFSBean() {
		super();
	}

	/* (non-Javadoc)
	 * @see javax.ejb.EntityBean#setEntityContext(javax.ejb.EntityContext)
	 */
	public void setEntityContext(EntityContext ctx)
		throws EJBException,
		RemoteException {
		this.ctx = ctx;
	}

	/* (non-Javadoc)
	 * @see javax.ejb.EntityBean#unsetEntityContext()
	 */
	public void unsetEntityContext() throws EJBException, RemoteException {
		this.ctx = null;

	}

	/* (non-Javadoc)
	 * @see javax.ejb.EntityBean#ejbRemove()
	 */
	public void ejbRemove()
		throws RemoveException,
		EJBException,
		RemoteException {

	}

	/* (non-Javadoc)
	 * @see javax.ejb.EntityBean#ejbActivate()
	 */
	public void ejbActivate() throws EJBException, RemoteException {

	}

	/* (non-Javadoc)
	 * @see javax.ejb.EntityBean#ejbPassivate()
	 */
	public void ejbPassivate() throws EJBException, RemoteException {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see javax.ejb.EntityBean#ejbLoad()
	 */
	public void ejbLoad() throws EJBException, RemoteException {
		AssignmentKey key = (AssignmentKey) ctx.getPrimaryKey();
		//String path = AssignmentFSUtils.getPath(key);
		FileSystemTraverser trav = new FileSystemTraverser();
		File root =null;
		try {
			root = trav.getAssignmentDir(key);

			File descriptionFile = new File(root, DESCRIPTION_FILENAME);
			File courseFile = new File(root, COURSE_FILENAME);
			BufferedReader reader = null;

			reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(descriptionFile)));
			name = reader.readLine();
			this.assignmentNumber = reader.readLine();
			this.course = CourseFSUtils.unserialize(new FileReader(courseFile));

		} catch (FileNotFoundException e) {
			ExceptionHandler.logException(e, this);
			throw new EJBException("Problem:",e);
		} catch (IOException e) {
			ExceptionHandler.logException(e, this);
			throw new EJBException("Problem:",e);
		}catch(TryException e){
			ExceptionHandler.logException(e, this);
			throw new EJBException("Problem:",e);
		}

	}

	/* (non-Javadoc)
	 * @see javax.ejb.EntityBean#ejbStore()
	 */
	public void ejbStore() throws EJBException, RemoteException {
		File thisDir = getDirectory();
		thisDir.mkdirs();
		File descriptionFile = new File(thisDir,DESCRIPTION_FILENAME);
		File courseFile = new File(thisDir,COURSE_FILENAME);
		File activities = new File(thisDir,ACTIVITY_DIRECTORY);
		PrintWriter writer = null;
		try {
			if (descriptionFile.getParentFile().exists()) {
				writer = new PrintWriter(new FileOutputStream(descriptionFile));
				writer.println(name);
				writer.println(this.assignmentNumber);
				writer.flush();
				writer.close();
				CourseFSUtils.serialize(this.course, new FileWriter(courseFile));
				if (!activities.exists()) {
					activities.mkdir();
				}
			} else
				throw new EJBException("Invalid Course.");
		} catch (IOException e) {
			descriptionFile.delete();
			ExceptionHandler.logException(e, this);
		}

	}

	private File getDirectory() {
		FileSystemTraverser traverser = new FileSystemTraverser();
		File rtVal = null;
		try {
			rtVal = traverser.getAssignmentDir(new AssignmentKey(this.course,this.assignmentNumber));
		} catch (TryException e) {
			ExceptionHandler.logException(e,this);
		}
		return rtVal;
		//return AssignmentFSUtils.getPath(new AssignmentKey(
			//this.course,
		//this.assignmentNumber));
	}

	public AssignmentKey ejbFindByPrimaryKey(AssignmentKey key)
		throws FinderException {
		try{
			FileSystemTraverser traver = new FileSystemTraverser();
		if (!(traver.getAssignmentDir(key).exists()))
			throw new FinderException("Does not exist");
		}catch(TryException e){
			throw new FinderException("Problem querying:"+e.getMessage());
		}
		return key;
	}

	public Collection ejbFindByCourseNumber(String courseNumber)
		throws FinderException {
		List lst = new ArrayList();
		try {
			File root = new File(TryFileSystem.getAssignmentDirectory());
			File terms[] = null, courses[] = null, assigns[] = null;
			terms = root.listFiles();
			for (int i = 0; i < terms.length; i++) {
				if (terms[i].isDirectory()) {
					courses = terms[i].listFiles();
					for (int k = 0; k < courses.length; k++) {
						if (courses[k].exists() && courses[k].isDirectory()) {
							try {
								lst.addAll(AssignmentFSUtils
									.findByCourseFolder(courses[k]));
								lst.addAll(CourseFSUtils
									.getSectionsFromGlobal(courses[k]));
							} catch (FileNotFoundException e1) {
								ExceptionHandler.logException(e1, this);
							} catch (IOException e1) {
								ExceptionHandler.logException(e1, this);
							}
						}
					}
				}
			}

		} catch (TryException e) {
			ExceptionHandler.logException(e, this);
			throw new FinderException(
				"Cannot Find CourseNumber problem with Query");
		}
		return lst;
	}

	/**
	 * Gets the unique Key associated with this assignment.
	 * Business method
	 * @ejb.interface-method  view-type = "both"
	 */
	public AssignmentKey getKey() {
		return new AssignmentKey(this.course, this.assignmentNumber);
	}
	/**
	 * Gets the name of this assignment.
	 * Business method
	 * @ejb.interface-method  view-type = "both"
	 */
	public String getAssignmentName() {
		return this.name;
	}
	/**
	 * Gets the Assignment Number of this assignment.
	 * 
	 * Business method
	 * @ejb.interface-method  view-type = "both"
	 */
	public String getAssignmentNumber() {
		return this.assignmentNumber;
	}
	/**
	 * Gets the Associated Course that this Assignment is part of.
	 * Business method
	 * @ejb.interface-method  view-type = "both"
	 */
	public CourseKey getAssociatedCourse() {
		return this.course;
	}
	/**
	 * Create method
	 * @ejb.create-method  view-type = "both"
	 */
	public AssignmentKey ejbCreate(CourseKey coursekey, String name, String ident)
		throws javax.ejb.CreateException {
		this.assignmentNumber = ident;
		this.name = name;
		this.course = coursekey;
		
		return new AssignmentKey(coursekey,ident);
	}
	/**
	 * Post Create method
	 */
	public void ejbPostCreate(CourseKey coursekey, String name, String ident)
		throws javax.ejb.CreateException {
		// TODO Auto-generated method stub
	}
}
