package com.mit.mimax.roles;

import java.io.Serializable;
import java.net.ConnectException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.mit.mimax.database.DBConnectionPool;
import com.mit.mimax.exceptions.MiMaxRoleException;

public class RoleManager implements Serializable
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -4858203816475917893L;

	public static String[] getUserRoles(String userName) throws ConnectException,
			SQLException, MiMaxRoleException 
	{
		Connection con = DBConnectionPool.getConnection();
		try
		{
			String sql = "SELECT EMP_NO FROM EMPLOYEE_MASTER WHERE USER_ID = '"
					+ userName + "'" + " AND PERSONAL_STATUS = 'ACTIVE'";
			Statement statement = con.createStatement();
			ResultSet resultSet = statement.executeQuery(sql);
			resultSet.next();
			int empNo = resultSet.getInt("EMP_NO");
			sql = "SELECT distinct(pr.policylist_policy_id) pol "
					+ "FROM pol_emp_role_details er, pol_policy_pol_role pr "
					+ "WHERE er.role_id = pr.rolelist_role_id AND er.emp_no = " + empNo + " "
					+ "UNION " + "SELECT ep.policy_id pol "
					+ "FROM pol_emp_policy_details ep " + "WHERE ep.emp_no =  " + empNo;
			//System.out.println(sql);
			statement.clearBatch();
			ResultSet policyList = statement.executeQuery(sql);
			List<String> list = new ArrayList<String>();
			while(policyList.next())
			{
				list.add(policyList.getString("POL"));
				//System.out.println("Added !!!");
			}
			con.close();
			resultSet.close();
			policyList.close();
			return (String[]) list.toArray(new String[list.size()]);
		}
		catch(Exception ex)
		{
			con.close();
			ex.printStackTrace();
			throw new MiMaxRoleException();
		}
	}
}
