<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import = "com.egurkha.admin.DeleteUserBean"%>
<%@ page import="net.sf.json.JSONObject"%>
<%@ page import="com.eg.IniFile"%>
<%@ page import="com.eg.EgInstallInfo"%>
<%@ page import="com.eg.EgUuidInfo"%>
<%@ page import="java.text.*"%>
<%@ page import="java.io.*"%>
<%@ 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);
	
	boolean showDebugInfo=true;
	String[] uname = request.getParameterValues("uname");
	if(uname != null && uname.length>0)
	{
		if(showDebugInfo)
		{
			logToErrorFile("");
			logToErrorFile("Delete user process page is called");
			logToErrorFile("Delete user process page - user names selected from tree " + Arrays.asList(uname));
		}
		EgUuidInfo uuidInfo = new EgUuidInfo();
		Set foundUsers = new TreeSet();
		for(int i=0;i<uname.length;i++)
		{
			String selectedUser = (String)uname[i];
			if(uuidInfo.isSuperOrg(selectedUser))
			{
				ArrayList allUsersUnderThisUser = uuidInfo.getAllSubOrgsAndUsers(selectedUser,true);
				if(allUsersUnderThisUser != null && !allUsersUnderThisUser.isEmpty())
				{
					foundUsers.addAll(allUsersUnderThisUser);
				}
			}
			foundUsers.add(selectedUser);
		}
		uname = (String[])foundUsers.toArray(new String[foundUsers.size()]);

		Set upwardParents = new TreeSet();
		boolean isOrgSelected=false;
		boolean isOuSelected=false;
		Set allUsers = new TreeSet();

		boolean whileDeletingOrgs=false;
		boolean whileDeletingOus=false;
		IniFile inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_services.ini");
		String mgrMode = inifile.getValue("MISC_ARGS","eGMgrModel");
		if(mgrMode != null && mgrMode.trim().equalsIgnoreCase("msp"))
		{
			String allowDeleteOrg = inifile.getValue("MISC_ARGS","AllowDeleteOrg");
			if(allowDeleteOrg != null && (allowDeleteOrg.trim().equalsIgnoreCase("yes") || allowDeleteOrg.trim().equalsIgnoreCase("true") || allowDeleteOrg.trim().equalsIgnoreCase("y") || allowDeleteOrg.trim().equalsIgnoreCase("t")))
			{
				String deleteOrg = inifile.getValue("MISC_ARGS","DeleteOrg");
				if(deleteOrg != null && (deleteOrg.trim().equalsIgnoreCase("yes") || deleteOrg.trim().equalsIgnoreCase("true") || deleteOrg.trim().equalsIgnoreCase("y") || deleteOrg.trim().equalsIgnoreCase("t")))
				{
					whileDeletingOrgs=true;
				}
				else
				{
					whileDeletingOus=true;
				}
			}
		}
		else
		{
			String deleteOrg = inifile.getValue("MISC_ARGS","DeleteSubOU");
			if(deleteOrg != null && (deleteOrg.trim().equalsIgnoreCase("yes") || deleteOrg.trim().equalsIgnoreCase("true") || deleteOrg.trim().equalsIgnoreCase("y") || deleteOrg.trim().equalsIgnoreCase("t")))
			{
				whileDeletingOus=true;
			}
		}

		ArrayList selectedOrgsToDelete = new ArrayList();
		ArrayList selectedOusToDelete = new ArrayList();
		for(int i=0;i<uname.length;i++)
		{
			String selectedUser = (String)uname[i];
			if(uuidInfo.isSuperOrg(selectedUser))
			{
				if(whileDeletingOrgs || whileDeletingOus)
				{
					selectedOrgsToDelete.add(selectedUser);
				}
				isOrgSelected=true;
			}
			else if(uuidInfo.isOrg(selectedUser))
			{
				if(whileDeletingOus)
				{
					selectedOusToDelete.add(selectedUser);
					ArrayList subOrgAndUsers = uuidInfo.getAllSubOrgsAndUsers(selectedUser);
					if(subOrgAndUsers != null && !subOrgAndUsers.isEmpty())
					{
						for(int j=0;j<subOrgAndUsers.size();j++)
						{
							selectedOusToDelete.add(subOrgAndUsers.get(j));
						}
					}
				}
				isOuSelected=true;
			}
			List allUpperNames = uuidInfo.getOrgNames(selectedUser,true);
			if(allUpperNames != null && !allUpperNames.isEmpty())
			{
				allUpperNames.remove(selectedUser);
				if(showDebugInfo)
				{
					logToErrorFile(selectedUser + " associated upward parents are " + allUpperNames);
				}
				if(!allUpperNames.isEmpty())
				{
					upwardParents.addAll(allUpperNames);

					HashMap sharedUsersMap = uuidInfo.getSharedUsersForAllOrgs();
					for (int k=0;k<allUpperNames.size();k++)
					{
						String orgName = (String)allUpperNames.get(k);
						ArrayList sharedUsersList = (ArrayList)sharedUsersMap.get(orgName);
						if (sharedUsersList != null && sharedUsersList.size() > 0)
						{
							upwardParents.addAll(sharedUsersList);
						}
					}
				}
			}
			allUsers.add(selectedUser);
			ArrayList allUsersUnderThisUser = uuidInfo.getAllSubOrgsAndUsers(selectedUser,true);
			if(allUsersUnderThisUser != null && !allUsersUnderThisUser.isEmpty())
			{
				allUsers.addAll(allUsersUnderThisUser);
			}
		}
//		Set upwardParents = new TreeSet();
		Set uniqueValues = new TreeSet();
		Iterator itr = allUsers.iterator();
		while(itr.hasNext())
		{
			String selectedUser = (String)itr.next();
//			List allUpperNames = uuidInfo.getOrgNames(selectedUser,true);
//			if(allUpperNames != null && !allUpperNames.isEmpty())
//			{
//				if(showDebugInfo)
//				{
//					logToErrorFile(selectedUser + " associated upward parents are " + allUpperNames);
//				}
//				upwardParents.addAll(allUpperNames);
//			}
			ArrayList subOrgAndUsers = uuidInfo.getAllSubOrgsAndUsers(selectedUser);
			if(subOrgAndUsers != null && !subOrgAndUsers.isEmpty())
			{
				uniqueValues.addAll(subOrgAndUsers);
			}
			uniqueValues.add(selectedUser);
		}

		ArrayList finalListOfUsers = new ArrayList();
		finalListOfUsers.addAll(uniqueValues);

		//Below usernames and organization will never be deleted as they are default usernames and organizations
		finalListOfUsers.remove("admin");
		finalListOfUsers.remove("supermonitor");
		finalListOfUsers.remove("egsm");
		finalListOfUsers.remove("egenterprise");

		Set deletElementsOfUsers = new TreeSet();
		for(int i=0;i<finalListOfUsers.size();i++)
		{
			String selectedUser = (String)finalListOfUsers.get(i);
			if(whileDeletingOrgs)
			{
				String rootUser = uuidInfo.getSuperOU(selectedUser,true);
				if(rootUser == null || rootUser.length()==0 || selectedOrgsToDelete.contains(rootUser))
				{
					deletElementsOfUsers.add(selectedUser);
				}
			}
			else if(whileDeletingOus && ((uuidInfo.isOrg(selectedUser) && selectedOusToDelete.contains(selectedUser)) || (uuidInfo.isSuperOrg(selectedUser) && selectedOrgsToDelete.contains(selectedUser))))
			{
				deletElementsOfUsers.add(selectedUser);
			}
			else
			{
				boolean added=false;
				String immediateParent = uuidInfo.getDirectDependentOU(selectedUser);
				if(whileDeletingOus && selectedOusToDelete.contains(immediateParent))
				{
					added=true;
					deletElementsOfUsers.add(selectedUser);
				}
				if(!added && (whileDeletingOrgs || whileDeletingOus))
				{
					String rootUser = uuidInfo.getSuperOU(selectedUser,true);
					if(rootUser == null || rootUser.length()==0 || selectedOrgsToDelete.contains(rootUser))
					{
						deletElementsOfUsers.add(selectedUser);
					}
				}
			}
		}

		uname = (String[])finalListOfUsers.toArray(new String[finalListOfUsers.size()]);
		if(showDebugInfo)
		{
			logToErrorFile("is organizaation selected to get deleted? " + isOrgSelected);
			logToErrorFile("is organization unit selected to get deleted? " + isOuSelected);
			logToErrorFile("selected users and their siblings are " + Arrays.asList(uname));
			logToErrorFile("selected associated upward parents of all selected users are " + upwardParents);
		}

		new DeleteUserBean(uname,deletElementsOfUsers,_user,request,session).deleteUser(true,isOrgSelected,isOuSelected,upwardParents);
	}
	JSONObject rootJSON = new JSONObject();
	rootJSON.put("success","true");
	out.println(rootJSON);
%>

<%!
	void logToErrorFile(String msg)
	{
		String autoDeleteLogFile = EgInstallInfo.getInstallDir() + "/manager/logs/DeleteUserLogFile.log";
		File ff = new File(autoDeleteLogFile);
//		if(recreatefile)
//		{
//			recreatefile=false;
//			ff.delete();
//		}
		if(ff != null && ff.length() >= 5000000)
		{
			try
			{
				EgInstallInfo.fileRename(autoDeleteLogFile,autoDeleteLogFile+".1");
			}
			catch (Exception grr)
			{
				grr.printStackTrace();
			}
		}
		ff = null;
		PrintWriter logWriter;
		try
		{
			logWriter = new PrintWriter(new FileWriter(autoDeleteLogFile, true));
		}
		catch (Exception e)
		{
			System.err.println("Cannot open log file " + autoDeleteLogFile);
			return;
		}
		if(msg == null || msg.trim().length()==0)
		{
			logWriter.println(" ");
		}
		else
		{
			logWriter.println(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date()) + " " + msg);
		}
		logWriter.close();
	}
%>