//----------------------------BEGIN LICENSE----------------------------
/* 
 * Willow : the Open Source WorkFlow Project
 * Distributable under GNU LGPL license by gun.org
 *
 * Copyright (C) 2004-2010 huihoo.org 
 * Copyright (C) 2004-2010  ZosaTapo <dertyang@hotmail.com> 
 * 
 * ====================================================================
 * Project Homepage : http://www.huihoo.org/willow
 * Source Forge     : http://sourceforge.net/projects/huihoo
 * Mailing list     : willow@lists.sourceforge.net 
 */
//----------------------------END  LICENSE-----------------------------
package org.huihoo.workflow.coreImpl.usermodel;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import org.huihoo.commons.jdbc.JDBCFactory;
import org.huihoo.commons.jdbc.JDBCUtilities;
import org.huihoo.workflow.SchemaContext;
import org.huihoo.workflow.server.WorkflowSession;
import org.huihoo.workflow.store.WorkflowUserDatabase;
import org.huihoo.workflow.usermodel.WorkflowDepartment;
import org.huihoo.workflow.usermodel.WorkflowGroup;
import org.huihoo.workflow.usermodel.WorkflowParticipant;
import org.huihoo.workflow.usermodel.WorkflowRank;
import org.huihoo.workflow.usermodel.WorkflowRole;


public class WorkflowParticipantImpl extends WorkflowParticipant
{

	public final static WorkflowParticipant NULL_PARTICIPANT = new WorkflowParticipantImpl(null,null, null, null, null, null);
	// ----------------------------------------------------------- Constructors

	/**
	 * The full name of this user.
	 */
	protected String fullName = null;

	/**
	 * The logon password of this user.
	 */
	protected transient String password = null;

	/**
	 * Package-private constructor used by the factory method in
	 * {@link WorkflowUserDatabase}.
	 *
	 * @param database The {@link WorkflowUserDatabase} that owns this user
	 * @param userid   Logon userid of the new user
	 * @param username Logon username of the new user
	 * @param password Logon password of the new user
	 * @param fullName Full name of the new user
	 */
	public WorkflowParticipantImpl(
	WorkflowSession session,
		WorkflowUserDatabase database,
		String userid,
		String username,
		String password,
		String fullName)
	{
		this(session,database, userid, username, password, fullName, null);
	}
	public WorkflowParticipantImpl(
	WorkflowSession session,
	WorkflowUserDatabase database,
		String userid,
		String username,
		String password,
		String fullName,
		String description)
	{
		super(userid, username);
		this.session =session;
		this.database = database;
		setFullName(fullName);
		setPassword(password);
		setDescription(description);
	}

	// ----------------------------------------------------- Instance Variables

	/**
	 * The {@link SpiUserDatabaseImpl_RT} that owns this user.
	 */
	protected transient  WorkflowUserDatabase database = null;
	protected transient  WorkflowSession session;
	
	/**
	 * The set of {@link Group}s that this user is a member of.
	 */
	protected ArrayList groups = null;

	/**
	 * The set of {@link Department}s that this user is a member of.
	 */
	protected ArrayList departments = null;

	/**
	 * The set of {@link WorkflowRole}s that this user is a member of.
	 */
	protected ArrayList roles = null;

	/**
	 * The id set of {@link WorkflowPackage}s that this user is a administrator member of.
	 */
	protected ArrayList packages = new ArrayList();

	/**
	 * The set of {@link Rank}s that this user is a member of.
	 */
	protected WorkflowRank rank;

	protected boolean superAdministrator = false;

	// ------------------------------------------------------------- Properties

	/**
	 * Return the full name of this user.
	 */
	public String getFullName()
	{
		return (this.fullName);
	}

	/**
	 * jSet the full name of this user.
	 *
	 * @param fullName The new full name
	 */
	public void setFullName(String fullName)
	{

		this.fullName = fullName;

	}

	/**
	 * Return the logon password of this user, optionally prefixed with the
	 * identifier of an encoding scheme surrounded by curly braces, such as
	 * <code>{md5}xxxxx</code>.
	 */
	public String getPassword()
	{

		return (this.password);

	}

	/**
	 * jSet the logon password of this user, optionally prefixed with the
	 * identifier of an encoding scheme surrounded by curly braces, such as
	 * <code>{md5}xxxxx</code>.
	 *
	 * @param password The new logon password
	 */
	public void setPassword(String password)
	{

		this.password = password;

	}

	/**
	 * Return the set of {@link Group}s to which this user belongs.
	 */
	public Iterator getGroups()
	{
		if (groups == null)
		{
			groups = new ArrayList();
			genGroupTree(groups);
		}

		return (groups.iterator());
	}

	/**
	 * Return the {@link WorkflowUserDatabase} within which this User is defined.
	 */
	public WorkflowUserDatabase getUserDatabase()
	{

		return (this.database);

	}

	// --------------------------------------------------------- Public Methods

	/**
	 * Add a new {@link Group} to those this user belongs to.
	 *
	 * @param group The new group
	 */
	public void addGroup(WorkflowGroup group)
	{
	}

	/**
	 * Is this user in the specified group?
	 *
	 * @param group The group to check
	 */
	public boolean isInGroup(WorkflowGroup group)
	{
		if (groups == null)
		{
			getGroups();
		}
		synchronized (groups)
		{
			return (groups.contains(group));
		}
	}

	/**
	 * Remove a {@link Group} from those this user belongs to.
	 *
	 * @param group The old group
	 */
	public void removeGroup(WorkflowGroup group)
	{
	}

	/**
	 * Remove all {@link Group}s from those this user belongs to.
	 */
	public void removeGroups()
	{

	}

	public WorkflowRank getRank()
	{
		return rank;
	}

	public void setRank(WorkflowRank userRank)
	{
		this.rank = userRank;
	}

	public void setSuperAdministrator(boolean superAdministrator)
	{
		this.superAdministrator = superAdministrator;
	}

	public boolean isAdministrator(String packageID)
	{
		if (superAdministrator)
		{
			return true;
		}

		return packages.contains(packageID);
	}

	public void addPackage(String packageID)
	{
		packages.add(packageID);
	}

	/**
	 * Add a new {@link Department} to those this user belongs to.
	 *
	 * @param department The new department
	 */
	public void addDepartment(WorkflowDepartment department)
	{
	}

	/**
	 * Is this user in the specified department?
	 *
	 * @param department The department to check
	 */
	public boolean isInDepartment(WorkflowDepartment department)
	{
		if (departments == null)
		{
			getDepartments();
		}
		synchronized (departments)
		{
			return (departments.contains(department));
		}
	}

	/**
	 * Remove a {@link Department} from those this user belongs to.
	 *
	 * @param department The old department
	 */
	public void removeDepartment(WorkflowDepartment department)
	{
	}

	/**
	 * Remove all {@link Department}s from those this user belongs to.
	 */
	public void removeDepartments()
	{
	}

	/**
	 * Add a new {@link WorkflowRole} to those this user belongs to.
	 *
	 * @param role The new role
	 */
	public void addRole(WorkflowRole role)
	{
	}

	/**
	 * Is this user in the specified role?
	 *
	 * @param role The role to check
	 */
	public boolean isInRole(WorkflowRole role)
	{
		if (roles == null)
		{
			getRoles();
		}
		synchronized (roles)
		{
			return (roles.contains(role));
		}

	}

	/**
	 * Remove a {@link WorkflowRole} from those this user belongs to.
	 *
	 * @param role The old role
	 */
	public void removeRole(WorkflowRole role)
	{
	}

	/**
	 * Remove all {@link WorkflowRole}s from those this user belongs to.
	 */
	public void removeRoles()
	{
	}

	/**
	 * Return the set of {@link Department}s to which this user belongs.
	 */
	public Iterator getDepartments()
	{
		if (departments == null)
		{
			departments = new ArrayList();
			genDepartmentTree(departments);
		}

		return (departments.iterator());
	}

	/**
	 * Return the set of {@link WorkflowRole}s to which this user belongs.
	 */
	public Iterator getRoles()
	{
		if (roles == null)
		{
			roles = new ArrayList();
			genRoleTree(roles);
		}

		return (roles.iterator());

	}
	//---------------------------------------------------------------------------------
	// generate WorkflowRole tree
	//---------------------------------------------------------------------------------	
	private void genRoleTree(ArrayList roles)
	{
		String strSQL =
			"SELECT vc_roleid FROM "
				+ database.getSchemaContext().getTableName(SchemaContext.SCHEMA_USER_ROLE)
				+ " "
				+ "WHERE vc_userid = ?";

		Connection conn = null;
		PreparedStatement pstmt = null;

		try
		{
			conn = JDBCFactory.getConnection(database.getStore());
			pstmt = conn.prepareStatement(strSQL);

			pstmt.setString(1, getUUID());

			ResultSet rs = pstmt.executeQuery();

			while (rs.next())
			{
				roles.add(database.findRole(session,rs.getString("vc_roleid")));
			}
		}
		catch (SQLException ex)
		{
			;
		}
		finally
		{
			JDBCUtilities.cleanupNoThrow(conn, pstmt);
		}
	}

	//---------------------------------------------------------------------------------
	// generate department tree
	//---------------------------------------------------------------------------------	
	private void genDepartmentTree(ArrayList departments)
	{
		String strSQL =
			"SELECT vc_departmenetid FROM "
				+ database.getSchemaContext().getTableName(SchemaContext.SCHEMA_USER_DEPARTMENT)
				+ " "
				+ "WHERE vc_userid = ?";

		Connection conn = null;
		PreparedStatement pstmt = null;

		try
		{
			conn = JDBCFactory.getConnection(database.getStore());
			pstmt = conn.prepareStatement(strSQL);

			pstmt.setString(1, getUUID());

			ResultSet rs = pstmt.executeQuery();

			while (rs.next())
			{
				departments.add(database.findDepartment(session,rs.getString("vc_departmenetid")));
			}
		}
		catch (SQLException ex)
		{
			;
		}
		finally
		{
			JDBCUtilities.cleanupNoThrow(conn, pstmt);
		}
	}

	//---------------------------------------------------------------------------------
	// generate group tree
	//---------------------------------------------------------------------------------
	private void genGroupTree(ArrayList groups)
	{
		String strSQL =
			"SELECT vc_groupid FROM "
				+ database.getSchemaContext().getTableName(SchemaContext.SCHEMA_USER_GROUP)
				+ " "
				+ "WHERE vc_userid = ?";

		Connection conn = null;
		PreparedStatement pstmt = null;

		try
		{
			conn = JDBCFactory.getConnection(database.getStore());
			pstmt = conn.prepareStatement(strSQL);

			pstmt.setString(1, getUUID());

			ResultSet rs = pstmt.executeQuery();

			while (rs.next())
			{
				groups.add(database.findGroup(session,rs.getString("vc_groupid")));
			}
		}
		catch (SQLException ex)
		{
			;
		}
		finally
		{
			JDBCUtilities.cleanupNoThrow(conn, pstmt);
		}
	}

	public String toString()
	{
		if (getName() != null)
		{
			return "name=" + getName();
		}
		else
		{
			return "uuid=" + uuid;
		}
	}
}
