<%@ page import="com.novell.webaccess.common.JSPConduit2,
				 com.novell.admin.ns.nds.NDSFilterResultModifier,
                 java.util.Enumeration,
                 com.novell.admin.ns.FilterResultModifier,
                 com.novell.application.console.snapin.*,
                 com.novell.emframe.dev.*,
                 com.novell.admin.ns.nds.NDSNamespace,
                 javax.naming.directory.*,
                 javax.naming.NamingEnumeration,
                 javax.naming.NamingException,
                 javax.naming.ldap.LdapContext,
                 java.util.Properties,
                 java.util.*,
                 com.novell.emframe.fw.FwUtils,
                 com.novell.emframe.fw.TargetChooserUtils"%>
<%@ taglib uri="/WEB-INF/iman.tld" prefix="iman" %>
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<iman:stringtable bundle="DevResources"/>
<iman:stringtable bundle="FwResources"/>
<%
   String errorMessage = null;
   JSPConduit2 c = JSPConduit2.getJSPConduit(request);
   c.stringTable("DevResources");
   c.stringTable("FwResources");
%>
<HTML>
<HEAD>
<LINK rel='stylesheet' href='<%= c.getModulesUrl() %>/dev/css/hf_style.css'>
<script type="text/javascript">

function checkonchange()
{
	var attr;
	 attr=window.parent.document.getElementById("TCChange").value;
	if(attr == "true")
	{
		window.parent.onTargetChooserTextChange(document.getElementById('quickFindTarget'));
	}

}


</script>
</HEAD>
<BODY topmargin="0" leftmargin="0" rightmargin="0" bottommargin="0">
<FORM id="quickfindform" name="quickfindform">
<SELECT style="width:350px; height:115px;" size="10" onChange="document.getElementById('quickFindTarget').value = this.value; checkonchange()">
<%!
	class LdapComparator implements Comparator 
	{
	 		public int compare(Object objOne, Object objTwo)
	 		{
	 			SearchResult srOne=(SearchResult) objOne;
	 			SearchResult srTwo=(SearchResult) objTwo;
		   		
	 			String ndapNameOne = MappingObject.LDAPNameToNDSName(srOne.getName());
	 			String ndapNameTwo = MappingObject.LDAPNameToNDSName(srTwo.getName());
		    
		    	return ndapNameOne.compareToIgnoreCase(ndapNameTwo);
		  	}
	}
%>

<%
   /*

   NOTE: first implemented using NDAP; To show first name last name, required N hits to eDirectory
   replaced with LDAP (only required one hit).

   MContext context = eMFrameFactory.getMContext(request);
   ObjectEntry treeOE = (ObjectEntry) context.getAuthenticationBroker().getAPIObject("NDSNamespace");
   NDSNamespace ns = (NDSNamespace) treeOE.getNamespace();


   NDSFilterResultModifier.FilterItemGroup filterItem = new NDSFilterResultModifier.FilterItemGroup();

   String compareFilter = null;
   String valueFilter = request.getParameter("quickFindFilter");
   if(request.getParameter("op").equals("startsWith"))
   {
      valueFilter += "*";
      compareFilter = FilterResultModifier.APPROX;
   }
   else
   {
      compareFilter = FilterResultModifier.EQUAL;
   }


   String attributeName = request.getParameter("quickFindAttribute");
   filterItem.addFilterItem(attributeName, compareFilter, valueFilter, null);

   // search step 2/4
   NDSFilterResultModifier.Filter filter = new NDSFilterResultModifier.Filter();
   filter.addFilterItemGroupPair(filterItem, null);

   // search step 3/4
   NDSFilterResultModifier resultModifier = new NDSFilterResultModifier("", filter, true);

   // search step 4/4
   ObjectEntry oe = ns.getObjectEntry("[root]");
   ObjectEntryEnumeration oee = ns.getChildren(oe, resultModifier);

   while (oee.hasMoreElements())
   {
      ObjectEntry objectEntry = (ObjectEntry) oee.nextElement();
      out.println("<OPTION>" + objectEntry.getFullName() + "<BR>");
   }
*/
%>


<%
   DirContext lctx=null;
	int cnt=0;
	String ndapName = null;
   try
   {
      MContext context = eMFrameFactory.getMContext(request);
      AuthenticationBroker broker=context.getAuthenticationBroker();
      lctx=(LdapContext) broker.getAPIObject("JndiLdap", (Properties) null);

      String attribute = request.getParameter("quickFindAttribute");
      String op = request.getParameter("op");
      String valueFilter = request.getParameter("quickFindFilter");
      
      // objectClass may be "*", a single class, or a comma-separated list of classes.
      String objectClass = request.getParameter("objectTypeName");

      TargetChooserUtils.addTCQuickFindAttribute(objectClass, attribute, context);

      // Construct the name part of the filter:  (cn=xx)  (cn=xx*)  (cn=*)  (!(cn=*))      
      String nameFilt;
      if(op.equals("isPresent"))
      {
      	nameFilt = "("+attribute+"=*)";
      }
      else if(op.equals("isNotPresent"))
      {
      	nameFilt = "(!("+attribute+"=*))";
      }
      else   // Operation "Equals" or "Starts With"
      {
        if(op.equals("startsWith"))
          valueFilter += "*";
        nameFilt="("+attribute+"="+valueFilter+")";
      }
      	
      // Construct the class part of the filter:
      //   empty if (objectClass=*)
      //   single class:  (objectClass=User)
      //   multiple:      (|(objectClass=Group)(objectClass=DynamicGroup)(objectClass=dynamicGroupAux))
      String classFilt;
      if(objectClass.equals("*"))					// No class
      {
         classFilt = null;
      }
      else if(objectClass.indexOf(",") == -1)		// Single class
      {
         classFilt="(objectClass=" + objectClass + ")";
      }
      else											// Multiple classes
      {
         classFilt = "(|";
         String[] classArr = objectClass.split(",");
         for (int i=0; i<classArr.length; i++)
         {
            classFilt += "(objectClass=" + classArr[i] + ")";
         }
         classFilt += ")";
      }
      
      // Now combine the name and class parts into a single LDAP filter.
      String filter;
      if (classFilt == null)
      	filter = nameFilt;
      else
      	filter = "(&" + nameFilt + classFilt + ")";
      
      SearchControls sc= new SearchControls(SearchControls.SUBTREE_SCOPE,
                           0, // count limit
                           0, // time limit
                           new String[]{"givenName", "SN"}, // attrs to return
                           false, // return obj
                           false); // dereference
      D.log("Executing Ldap search of entire tree.  Filter = "+filter);
      NamingEnumeration ne_ldap=lctx.search("", filter, sc);
      
      String doSort = request.getParameter("doSort");
     
	  List list = null;
	  Enumeration ne = null;
	  if(doSort.equalsIgnoreCase("true"))
	  {
		list = Collections.list(ne_ldap);
	  	Collections.sort(list, new LdapComparator());
	  	ne=Collections.enumeration(list);
	  }
	  else
	  {
		  ne = ne_ldap;
	  }
	  
      while (ne!=null && ne.hasMoreElements()&& cnt<500)
      {
         SearchResult sr=(SearchResult) ne.nextElement();

         Attribute attr1 = sr.getAttributes().get("givenName");
         Attribute attr2 = sr.getAttributes().get("SN");

         String givenName = "";
         if(attr1 !=null && attr1.size()>0)
         {
            givenName = (String)attr1.get(0);
         }

         String surname = "";
         if(attr2 !=null && attr2.size()>0)
         {
            surname = (String)attr2.get(0);
         }

         String name = sr.getName();
         //System.out.println("ldap name = "+name);
         ndapName = MappingObject.LDAPNameToNDSName(name);

         //System.out.println("ndap name = "+ndapName);

         String displayName = null;
         if(givenName==null || givenName.length()==0  || surname==null || surname.length()==0)
         {
            displayName = ndapName;
         }
         else
         {
            displayName = ndapName+" ("+givenName + " " + surname+")";
         }
        
         if (!(displayName.trim().equals("")))
         out.println("<OPTION value=\""+ndapName+"\">"+displayName);
         
         cnt++;
      }
      D.log("Number of entries returned (500 max): " + cnt);
   }
   catch(Throwable e)
   {
      com.novell.emframe.dev.D.log(e);
	  errorMessage = e.getMessage();
      // REMIND: what do do
   }
%>

</SELECT>
<INPUT type="text" id="quickFindTarget" name="quickFindTarget" style="width:350px" onchange="checkonchange();">
 <%if(cnt==1){%>
   	 <script> 
    	  document.getElementById('quickFindTarget').value ='<%=ndapName%>';
    	  checkonchange();
   	  </script>
<%}%>
<%if(errorMessage!=null){%>
	<SCRIPT>
		function showDetails()
		{
			var e = document.getElementById("trace");
            if (e!=null)
            {
               if (e.style.display=="block")
               {
                  e.style.display="none";
               }
               else
               {
                  e.style.display="block";
               }
            }
		}
		
  
	</SCRIPT>
	<br/><SPAN class="smalltext2d"><%= c.string("Book.internalError") %></SPAN><BR>
	<IMG type=image src="<%= c.getModulesUrl() + "/dev/images/" + c.string("Button.Details.image") %>"
		 alt="<%= c.string("Button.Details.alt") %>"
		 title="<%= c.string("Button.Details.alt") %>"
         style="cursor:hand"
		 id="btnDetails"
		 onClick="showDetails()">
	<div id="trace" style="display:none">
    <!-- inner html goes here -->

    <table border=1><tr><td><code><%= errorMessage %></code></td></tr></table><br>
	</div>
<%}errorMessage = null;%>
</FORM>
</BODY>
</HTML>
