/*
 * ListSearchResult.java
 *
 * Copyright 2011 John W Dawson
 *
 * This code is distributed under the terms of the GNU General Public License, version 3
 *
 * This class represents an individual search result
 */
 
import javax.naming.directory.*;
import java.util.*;
import java.util.regex.*;
public class ListSearchResult extends SearchResult implements Comparable<ListSearchResult>
{ 

  private static Pattern fieldPattern = Pattern.compile ("%(\\w+)%");

  private ConfigurationRecord configuration;
  private String displayFields;
  private StringBuffer displayBuff = new StringBuffer ();
  
  public ListSearchResult (SearchResult result, ConfigurationRecord configuration, Map<String, AddressBookField> fieldList)
  {
    super (result.getName(), result.getObject(), result.getAttributes());

    // Match all occurences of a field reference in the pattern for the display string
    Matcher matcher = fieldPattern.matcher (configuration.getElementValue ("displayfields"));
    while (matcher.find ())
    {
      // Replace the field reference with the actual value of the field (if any) in this entry
      String fieldValue = fieldList.get (matcher.group (1)).getValue (result);
      matcher.appendReplacement (displayBuff, fieldValue == null ? "" : fieldValue.replaceAll("\\\\","\\\\\\\\"));
    }
    
    // Add any remaining text
    matcher.appendTail (displayBuff);
  }
  
  public String getAttribute (String attribute)
  {
    try
    {   
      return String.valueOf (getAttributes().get(attribute).get());      
    }
    catch (Exception e)
    {
      return null;
    }
  }
  
  public String toString ()
  {
    return displayBuff.toString ();
  }
  
  public int compareTo (ListSearchResult compareResult)
  {
    int compare = toString().compareTo (compareResult.toString());
    return compare == 0 ? 1 : compare;
  }
  
  public boolean equals (ListSearchResult compareResult)
  {
    // Always return false to allow entries with duplicate names
    return false;
  }
}