<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import = "net.sf.json.*"%>
<%@ page import="com.egurkha.*"%>
<%@ page import="com.eg.EgMappingInfo"%>
<%@ page import="com.eg.MappingNameSorter"%>
<%@ page import="com.egurkha.util.StringUtils"%>
<%@ page import="com.egurkha.admin.DeleteUserElementDAO"%>
<%@ page import="java.util.*"%>
<%@ page import="com.eg.IniFile"%>
<%@ page import="com.eg.EgInstallInfo"%>
<%@ page import="com.eg.EgUuidInfo"%>
<%@ page import="com.eg.*"%>
<%@ page import="com.egurkha.*"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);

	response.setContentType("application/json;charset=UTF-8");

	HashMap allUsersRoleTypeMap = new HashMap();
	EgDbAdapterUI egDb=EgDbAdapterTypeUI.getObject();
	String str_conn = egDb.setConnection();
	try
	{
		allUsersRoleTypeMap = egDb.getAllUsersRoleTypeMap();
	}
	catch (Exception e)
	{
		e.printStackTrace();
	}
	egDb.releaseConnection(true);
	EgDbAdapterTypeUI.releaseObject(egDb);

	boolean showDebugInfo=false;
	String categoryType = request.getParameter("categoryType");
	if(showDebugInfo)
	{
		System.out.println();
		System.out.println("Category type : " + categoryType);
	}
	boolean filtering = (!StringUtils.isNull(categoryType) && !categoryType.equalsIgnoreCase("all"));

	JSONObject objectToServlet = new JSONObject();

	IniFile serviceinifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_services.ini");
	String managerModel = serviceinifile.getValue("MISC_ARGS","eGMgrModel");
	managerModel=(managerModel !=null && managerModel.equalsIgnoreCase("msp"))?"msp":"ent";
	if(showDebugInfo)
	{
		System.out.println("Manager model : " + managerModel);
	}
	EgUuidInfo egUuidInfo = new EgUuidInfo();
	IniFile inifile = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_uuid.ini");
	String subous[] = inifile.getVariables("ORG_EXPIRY_DATE");
	boolean noUsersConfigured=false;
	if(managerModel.equals("msp"))
	{
		String usersCheck[] = inifile.getVariables("ORGANIZATION_MAPPING");
		noUsersConfigured=(usersCheck != null && usersCheck.length==3 && subous != null && subous.length==1);
	}
	else
	{
		ArrayList siblings = egUuidInfo.getAllSubOrgsAndUsers("egenterprise",true);
		noUsersConfigured=(siblings != null && siblings.size()==3);
		if(noUsersConfigured)
		{
			if(showDebugInfo)
			{
				System.out.println("Other than default users, no other users were created under egenterprise organization");
			}
		}
	}
	String logged_in_username = UserRegistry.getInstance().getUser(request.getSession(false).getId(),true).getLoginID();
	if(managerModel.equalsIgnoreCase("msp") && logged_in_username.equals("egenterprise"))
	{
		logged_in_username="admin";
	}

	EgUserRole usrRole = _user.getUserRole();
	boolean hasAllComponentAccess = usrRole.hasAllComponentAccess();

	if(showDebugInfo)
	{
		System.out.println("login username : " + logged_in_username);
	}
	String init_logged_in_username=logged_in_username;
	String parentOUOfLoggedInUser = egUuidInfo.getDirectDependentOU(logged_in_username,true);

	//here i am building list of editable nodes in tree -  starts
	ArrayList removeFromEditableList = new ArrayList();
	removeFromEditableList.add(logged_in_username);
	if(!logged_in_username.equalsIgnoreCase("admin") && !hasAllComponentAccess && !egUuidInfo.isSuperOrg(logged_in_username,true))
	{
		if(!egUuidInfo.isOrg(logged_in_username,true))
		{
			if(egUuidInfo.isUser(logged_in_username,true))
			{
				String upParent = egUuidInfo.getDirectDependentOU(logged_in_username);
				ArrayList siblings = egUuidInfo.getAllSubOrgsAndUsers(upParent,true);
				if(siblings != null)
				{
					siblings.remove(logged_in_username);
					if(siblings.size()>1)
					{
						if(showDebugInfo)
						{
							System.out.println("here the login name is changed 1");
						}
						logged_in_username=upParent;
						removeFromEditableList.add(logged_in_username);
					}
				}
			}
		}
		else if(egUuidInfo.isOrg(logged_in_username,true))
		{
			ArrayList siblings = egUuidInfo.getAllSubOrgsAndUsers(logged_in_username,true);
			if(siblings != null)
			{
				siblings.remove(logged_in_username);
				if(siblings.size()>1)
				{
					removeFromEditableList.add(logged_in_username);
				}
			}
		}
	}

	//here i check if users are found under either egenterprise or other organizations -  starts
	if(egUuidInfo.isUser(logged_in_username,true))
	{
		ArrayList siblings = egUuidInfo.getAllSubOrgsAndUsers(logged_in_username,true);
		if(siblings != null)
		{
			if(siblings.size()==0)
			{
				String parentOUOfLoggedInUser1 = egUuidInfo.getDirectDependentOU(logged_in_username,true);
				siblings = egUuidInfo.getAllSubOrgsAndUsers(parentOUOfLoggedInUser1,true);
				siblings.remove(init_logged_in_username);
				siblings.remove(logged_in_username);
				if(parentOUOfLoggedInUser1 != null)
				{
					siblings.remove(parentOUOfLoggedInUser1);
				}
				if(siblings.size()==0)
				{
					noUsersConfigured=true;
				}
				else
				{
					if(showDebugInfo)
					{
						System.out.println("here the login name is changed 2");
					}
					logged_in_username=parentOUOfLoggedInUser1;
				}
			}
		}
	}
	else
	{
		ArrayList siblings = egUuidInfo.getAllSubOrgsAndUsers(logged_in_username,true);
		if(!logged_in_username.equalsIgnoreCase("admin") && !hasAllComponentAccess && siblings != null)
		{
			siblings.remove(logged_in_username);
			if(siblings.size()==0)
			{
				noUsersConfigured=true;
			}
			else if(siblings.size()==1)
			{
				if(egUuidInfo.isOrg(logged_in_username,true))
				{
					noUsersConfigured=false;
				}
				else
				{
					noUsersConfigured=true;
				}
			}
		}
	}
	objectToServlet.put("noUsersConfigured",noUsersConfigured);
	if(showDebugInfo)
	{
		System.out.println("logged in username is changed into : " + logged_in_username);
	}
	if(noUsersConfigured)
	{
		if(showDebugInfo)
		{
			System.out.println("No users have been configured in eG System");
		}
	}
	else
	{
		ArrayList superEditableUsers = new ArrayList();
		DeleteUserElementDAO elementDAO = new DeleteUserElementDAO();
		Hashtable categoryUsersHt = elementDAO.getUsersInfoDetails(logged_in_username,categoryType,managerModel,hasAllComponentAccess);
		if(showDebugInfo)
		{
			System.out.println("categoryUsersHt are : " + categoryUsersHt);
		}
		if(categoryUsersHt != null && categoryUsersHt.isEmpty())
		{
			objectToServlet.put("orgUsersNotFound",true);
		}
		else
		{
			TreeSet tempSet = new TreeSet();
			if(logged_in_username.equalsIgnoreCase("admin") || hasAllComponentAccess)
			{
				Iterator itr = categoryUsersHt.keySet().iterator();
				while(itr.hasNext())
				{
					String k = (String)itr.next();
					ArrayList alist = (ArrayList)categoryUsersHt.get(k);
					tempSet.addAll(alist);
				}
			}
			else
			{
				String superOrgName = egUuidInfo.getSuperOU(logged_in_username);
				if(superOrgName == null || superOrgName.trim().length()==0 || superOrgName.trim().equalsIgnoreCase("null"))
				{
					superOrgName = logged_in_username;
				}
				ArrayList alist = (ArrayList)categoryUsersHt.get(superOrgName);
				if(alist != null && !alist.isEmpty())
				{
					ArrayList siblingsTemp = egUuidInfo.getAllSubOrgsAndUsers(logged_in_username,true);
					if(siblingsTemp != null)
					{
						for(int i=0;i<alist.size();i++)
						{
							String s = (String)alist.get(i);
							if(siblingsTemp.contains(s))
							{
								tempSet.add(s);
							}
						}
					}
				}
			}
			superEditableUsers.addAll(tempSet);
		}
		superEditableUsers.remove(logged_in_username);
		superEditableUsers.remove(init_logged_in_username);
		if(showDebugInfo)
		{
			System.out.println("superEditableUsers     : " + superEditableUsers);
		}
		String subousandusers[] = inifile.getVariables("ORGANIZATION_MAPPING");
		TreeSet validUsersAndOus_category = new TreeSet();
		ArrayList editable_users = new ArrayList();
		editable_users.addAll(superEditableUsers);
		if(showDebugInfo)
		{
			System.out.println("final editable user nodes are " + editable_users);
		}
		if(!categoryType.equalsIgnoreCase("all"))
		{
			editable_users.clear();
			editable_users.addAll(superEditableUsers);

			for(int i=0;i<superEditableUsers.size();i++)
			{
				String key = (String)superEditableUsers.get(i);
				List allUpperNames = egUuidInfo.getOrgNames(key,true);
				if(allUpperNames != null && !allUpperNames.isEmpty())
				{
					validUsersAndOus_category.addAll(allUpperNames);
					validUsersAndOus_category.add(key);
				}
			}
		}
		ArrayList category_users = new ArrayList();
		category_users.addAll(editable_users);
		if(parentOUOfLoggedInUser != null)
		{
			editable_users.remove(parentOUOfLoggedInUser);
		}
		if(showDebugInfo)
		{
			System.out.println("editable_users : " + editable_users);
		}
		boolean orgUsersNotFound = (editable_users.size()==0);
		objectToServlet.put("orgUsersNotFound",orgUsersNotFound);
		if(orgUsersNotFound)
		{
			if(showDebugInfo)
			{
				System.out.println("Users are not found in the selected organization for this category " + categoryType);
			}
		}
		else
		{
			if(showDebugInfo)
			{
				System.out.println("Users are found in the selected organization for this category " + categoryType);
			}
			Set uniqueNames = new TreeSet();
			JSONArray editableNodes = new JSONArray();
			for(int i=0;i<editable_users.size();i++)
			{
				String str = (String)editable_users.get(i);
				List strList = egUuidInfo.getOrgNames(str);
				if(strList != null && !strList.isEmpty())
				{
					uniqueNames.addAll(strList);
				}
				uniqueNames.add(str);
				editableNodes.add(str);
				TreeSet myset = egUuidInfo.getAllUsersUnderOrg(str);
				//do not allow logged in user or its immediate parent to get selected
				myset.remove(logged_in_username);
				if(parentOUOfLoggedInUser != null)
				{
					myset.remove(parentOUOfLoggedInUser);
				}
				if(!myset.isEmpty())
				{
					uniqueNames.addAll(myset);
					editableNodes.addAll(myset);
				}
			}
			if(logged_in_username != null && editableNodes.contains(logged_in_username))
			{
				editableNodes.remove(logged_in_username);
			}
			TreeSet removeDuplicates = new TreeSet();
			removeDuplicates.addAll(editableNodes);
			editable_users.clear();
			editable_users.addAll(removeDuplicates);

			//do not allow logged in user or its immediate parent to get selected
			editable_users.remove(logged_in_username);
			if(parentOUOfLoggedInUser != null)
			{
				editable_users.remove(parentOUOfLoggedInUser);
			}
			objectToServlet.put("editableNodes",editableNodes);
			if(showDebugInfo)
			{
				if(editable_users.isEmpty())
				{
					System.out.println("No editable nodes found");
				}
				else
				{
					System.out.println("Editable nodes found are " + editable_users);
				}
			}
			String topLevelOrgs[] = inifile.getVariables("ORG_UUID");
			ArrayList superOrgs = new ArrayList();
			if(logged_in_username != null && !logged_in_username.equalsIgnoreCase("admin") && !hasAllComponentAccess)
			{
				superOrgs.add(logged_in_username);
			}
			else
			{
				if(managerModel.equalsIgnoreCase("msp"))
				{
					if(categoryType.equalsIgnoreCase("all"))
					{
						if(topLevelOrgs != null)
						{
							superOrgs.addAll(Arrays.asList(topLevelOrgs));
						}
						ArrayList siblings = egUuidInfo.getAllSubOrgsAndUsers("egenterprise",true);
						if(siblings != null && siblings.size()==3)
						{
							superOrgs.remove("egenterprise");
						}
					}
					else
					{
						if(!categoryUsersHt.isEmpty())
						{
							if(topLevelOrgs != null)
							{
								for(int i=0;i<topLevelOrgs.length;i++)
								{
									String s = topLevelOrgs[i];
									if(categoryUsersHt.containsKey(s))
									{
										superOrgs.add(s);
									}
								}
							}
						}
					}
				}
				else if(managerModel.equalsIgnoreCase("ent"))
				{
					if(categoryType.equalsIgnoreCase("all"))
					{
						ArrayList siblings = egUuidInfo.getAllSubOrgsAndUsers("egenterprise",true);
						if(siblings != null && siblings.size()>3)
						{
							superOrgs.add("egenterprise");
						}
					}
					else
					{
						if(!categoryUsersHt.isEmpty() && categoryUsersHt.containsKey("egenterprise"))
						{
							superOrgs.add("egenterprise");
						}
					}
				}
			}
			if(showDebugInfo)
			{
				System.out.println("Tree has to be built for the organizations " + superOrgs);
			}
			JSONArray exportDataArr = new JSONArray();
			for(int i=0;i<superOrgs.size();i++)
			{
				JSONObject exportDataObj = new JSONObject();
				String orgname = (String)superOrgs.get(i);
				if(!categoryType.equalsIgnoreCase("all"))
				{
					String associatedSuperOrgName = egUuidInfo.getSuperOU(orgname,true);
					if(associatedSuperOrgName == null || associatedSuperOrgName.trim().length()==0 || associatedSuperOrgName.trim().equalsIgnoreCase("null"))
					{
						associatedSuperOrgName=orgname;
					}
					if(!categoryUsersHt.containsKey(orgname) && !categoryUsersHt.containsKey(associatedSuperOrgName))
					{
						continue;
					}
				}
				if (orgname.equalsIgnoreCase("egenterprise"))
				{
					exportDataObj.put("text",_mapping.getTextDescription("admin.user.egenterprise"));
				}
				else
				{
					exportDataObj.put("text",orgname);
				}
				exportDataObj.put("id",orgname);
				if(allUsersRoleTypeMap.containsKey(orgname))
				{
					exportDataObj.put("role",(String)allUsersRoleTypeMap.get(orgname));
				}
				else
				{
					exportDataObj.put("role","-");
				}
				if(egUuidInfo.isSuperOrg(orgname))
				{
					exportDataObj.put("iconCls","iconDomain");
				}
				else if(egUuidInfo.isOrg(orgname))
				{
					exportDataObj.put("iconCls","iconOtherUsers");
				}
				else
				{
					exportDataObj.put("iconCls","iconUxUser");
				}
				if(editable_users.contains(orgname))
				{
					exportDataObj.put("checked",false);
				}
				exportDataObj.put("expanded",true);

				JSONArray rootUserObjectArray = new JSONArray();
				if (categoryType.equalsIgnoreCase("expired"))
				{
					TreeSet expiredUserSet = egUuidInfo.getAllExpiredUsers();
					if (expiredUserSet != null && !expiredUserSet.isEmpty())
					{
						rootUserObjectArray = egUuidInfo.buildTreeJsonForExpiredUsers(orgname,true,expiredUserSet);
					}
				}
				else
				{
					rootUserObjectArray = egUuidInfo.buildTreeJsonForAllUsers(orgname,logged_in_username,true,categoryType);
				}
				exportDataObj.put("children",rootUserObjectArray);
				exportDataArr.add(exportDataObj);
			}
			objectToServlet.put("exportDataArr",exportDataArr);
		}
	}
	objectToServlet.put("success","true");
	out.println(objectToServlet.toString());
%>
<%!
	public JSONArray buildTreeJson(String orgname,boolean showExpired,ArrayList editable_users,IniFile inifile,Set uniqueNames,boolean filtering,EgUuidInfo egUuidInfo,String parentOUOfLoggedInUser,String logged_in_username,String init_logged_in_username,HashMap allUsersRoleTypeMap,TreeSet validUsersAndOus_category,String categoryType, String subous[], String subousandusers[])
	{
		ArrayList firstlist = new ArrayList();
		firstlist.addAll(Arrays.asList(subous));
		ArrayList secondlist = new ArrayList();
		secondlist.addAll(Arrays.asList(subousandusers));
		secondlist.removeAll(firstlist);
		if(orgname == null || orgname.trim().length()==0 || orgname.trim().toLowerCase().equals("null"))
		{
			return null;
		}

		JSONArray jArray = new JSONArray();
		ArrayList subOuList = egUuidInfo.getDirectSubOU(orgname);

		if(init_logged_in_username != null && subOuList != null && subOuList.contains(init_logged_in_username))
		{
			subOuList.remove(init_logged_in_username);
		}

		for(int i=0;i<secondlist.size();i++)
		{
			String t = (String)secondlist.get(i);
			String t1 = inifile.getValue("ORGANIZATION_MAPPING",t);
			if(t1.equalsIgnoreCase(orgname) && !t.equalsIgnoreCase("admin") && !t.equalsIgnoreCase("supermonitor") && !t.equalsIgnoreCase("egsm"))
			{
				if(init_logged_in_username != null)
				{
					if(!init_logged_in_username.equalsIgnoreCase(t) && !subOuList.contains(t))
					{
						subOuList.add(t);
					}
				}
				else if(!subOuList.contains(t))
				{
					subOuList.add(t);
				}
			}
		}
		if(filtering)
		{
			for(int i=subOuList.size()-1;i>=0;i--)
			{
				String now = (String)subOuList.get(i);
				if(!uniqueNames.contains(now))
				{
					subOuList.remove(now);
				}
			}
		}
		if(parentOUOfLoggedInUser != null && orgname.equalsIgnoreCase(parentOUOfLoggedInUser) && subOuList.contains(logged_in_username))
		{
			subOuList.clear();
			subOuList.add(logged_in_username);
		}
		if(!categoryType.equalsIgnoreCase("all"))
		{
			for(int k=subOuList.size()-1;k>=0;k--)
			{
				String user = (String)subOuList.get(k);
				if(!validUsersAndOus_category.contains(user))
				{
					subOuList.remove(user);
				}
			}
		}
		int subOuListSize = subOuList.size();
		int count = 0;
		while (count < subOuListSize)
		{
			String subOU = (String)subOuList.get(count);
			String displayName = subOU;
			if (subOU.startsWith("samlsso/"))
			{
				int idx = subOU.indexOf("/");
				displayName = subOU.substring(idx+1) + " (SAML)";
			}
			else if (subOU.indexOf("/") != -1)
			{
				if (subOU.indexOf("/Grp/") != -1)
				{
					String grpDelimiter = "/Grp/";
					int idx = subOU.indexOf(grpDelimiter);
					String str_uname_A = subOU.substring(0,idx);
					int nextIdx = idx + grpDelimiter.length();
					String str_uname_B = subOU.substring(nextIdx);
					displayName = str_uname_A + "/" + str_uname_B + " (Group)";
				}
			}
			JSONArray childArray = buildTreeJson(subOU,showExpired,editable_users,inifile,uniqueNames,filtering,egUuidInfo,parentOUOfLoggedInUser,logged_in_username,init_logged_in_username,allUsersRoleTypeMap,validUsersAndOus_category,categoryType,subous,subousandusers);
			JSONObject obj = new JSONObject();
			String uvalidtill = "";
			obj.put("id",subOU);
			obj.put("text",displayName);
			obj.put("name",subOU);
			obj.put("uvalidtill",uvalidtill);
			if(allUsersRoleTypeMap.containsKey(subOU))
			{
				obj.put("role",(String)allUsersRoleTypeMap.get(subOU));
			}
			else
			{
				obj.put("role","-");
			}
			if(editable_users.contains(subOU))
			{
				obj.put("checked",false);
			}
			ArrayList nextsubOuList = egUuidInfo.getAllSubOrgsAndUsers(subOU,true);
			if(egUuidInfo.isOrg(subOU))// && nextsubOuList != null && !nextsubOuList.isEmpty())
			{
				obj.put("expanded", true);
				obj.put("children", childArray);
				obj.put("iconCls", "iconOtherUsers");
			}
			else
			{
				obj.put("leaf", "true");
				//obj.put("iconCls", "iconLeafImg");
				if(egUuidInfo.hasOURole(subOU))
				{
					obj.put("iconCls", "iconUxAdminUser");
				}
				else
				{
					obj.put("iconCls", "iconUxUser");
				}
			}
			jArray.add(obj);
			count++;
		}
		return jArray;
	}
%>



