/**
 *  Filter records where selected field matches the given regular expression.
 *  THIS AGENT IS NOT COMPLETE.
 *  It is skeleton for a wrapper that computes result from request.
 *  You must complete the go(..) method self dependently.
 *  Generated 2002.9.17  by Sight 2.0, Ulm university.
 */
package impl.manipulators;

import Sight.Agents.*;
import Sight.Agents.Prototypes.*;
import Sight.Agents.Signals.*;
import Sight.dds.*;
import java.io.*;
import java.util.regex.*;
import Sight.Agents.util.*;

public class stringFilter extends Wrapper implements Serializable, Fast {
  /* Data structure to pass query to this robot. */
  public class Request extends Sight.Request implements java.io.Serializable {
        /** Regular expression that must match filter subject. Normaly specified. */
        public CharSequence Filter;
        /** Field that must match the 'Filter' regular exprassion */
        public CharSequence Filter_object;
        /** Matching condition. */
        public CharSequence Condition = "yes";

       /** Submit request, compute key by SHA digesting algorithm. */
       public Sight.Agents.Request submit() { return Sight.Agents.Request.submit(Public, this, getKey()); };
       /** Submit request with the known key. */
       public Sight.Agents.Request submit(String key)
        { return Sight.Agents.Request.submit(Public, this, key); };
       };

  /** Get default request for this robot. */
  public static Request getDefaultRequest() {
     return Public.getRequest(); }
  private Request getRequest() { return new Request(); }; // must be non static

    /** Type definitions for Request. */
   public dStructure getRequestDds() {
    return new Sight.dds.Records(true,
     new dField[] {
        new dField("Filter","CharSequence","Regular expression that must match filter object. Syntax defined in http://java.sun.com/j2se/1.4/docs/api/java/util/regex/Pattern.html",""),
        new dField("Condition","CharSequence","The filter condition","yes",
         new String[] {"yes","no"},
         new String[] { "must match","must NOT match"}),
        new dField("Filter_object","CharSequence","Field that must match the \'Filter\' regular exprassion","")
        }
    );
   }


 /* Record type, used in results for this robot. */
 /* The result of this robot is an array of records. */
  public static class Record extends Sight.Record implements Serializable {
        /** Filter, used for selection */
        public CharSequence Filter;
        /** Field that passed the filter */
        public CharSequence Filter_object;
        /** Condition (yes, no) */
        public CharSequence Condition;
      };
      /** The result of this robot. */
      public static class Result extends Sight.Result implements Serializable {
         public Record[] a; // array of results.
         /** Create report for one record. */
         public CharSequence getReportForRecord(Object ro, int level)
          { Record r = (Record) ro;
            String cnd = "<font color=\"#A00000\"><b>"+r.Condition+"</b></font> '"+r.Filter+"'";
           switch (level) {
              case 0:  return "Matches "+cnd;
              case 1:  return r.Filter_object+" MATHCES "+cnd;
              default:
               {
                 StringBuffer b = new StringBuffer(
                 "Filter, used for selection: "+
                 r.Filter+"<br>Field that passed the filter: "+
                 r.Filter_object);
                 return b;
               }
            }
          };
      }
    /** Type definitions for Result. */
   public dStructure getResultDds() {
    return new Sight.dds.Records(false,
     new dField[] {
        new dField("Filter","CharSequence","Filter, used for selection",""),
        new dField("Filter_object","CharSequence","Field that passed the filter",""),
        new dField("Condition","CharSequence","Must match or must NOT match (yes or no)","")
        }
    );
   }

   String pPattern = null;
   Pattern pattern = null;

   /** Implementation of the central go method.  */
   public Object go(Object o_request) throws Exception
    {
     Request request = (Request) o_request;
     Result  result  = new Result();
     Record record = new Record();

     String test = request.Filter.toString();
     if (pPattern==null || !pPattern.equals(test))
      {
        pPattern = test;
        pattern = Pattern.compile(pPattern, Pattern.CASE_INSENSITIVE);
      };

     if (request.Filter_object==null)
      {
        p("ERROR: filter object was not set.");
        throw new FatalAgentException("Filter object not set!");
      }

     Matcher m = pattern.matcher(request.Filter_object);

     boolean matches = m.find();
     if (request.Condition!=null &&
         request.Condition.toString().trim().equalsIgnoreCase("no"))
          matches = !matches;

     if (!matches)
      { p(request.Filter_object+" does not match "+request.Condition+":' "+pPattern+"'");
        return EMPTY;
      } else
         p(request.Filter_object+" MATHCES '"+request.Condition+":' "+pPattern+"'");

     result.a = new Record[1];
     result.a[0] = record;

     record.Filter =  request.Filter;
     record.Condition = request.Condition;
     record.Filter_object = request.Filter_object;
     // set the agent signature:
     result.setAgentSignature("<b>String filter <i>"+pPattern+"</i></b> ");
     return result;
    };


  final Result EMPTY;

  public stringFilter() {
   setDescription("Filter records where selected field matches the given regular expression.");
   setMasterURL("http://java.sun.com/j2se/1.4/docs/api/java/util/regex/Pattern.html");
   // this robot newer uses caching:
   setWriteCache(false);
   setReadCache(false);

   EMPTY = new Result();
   EMPTY.a = new Record[0];

   };
  /** Public instance of agent for user. */
  public static stringFilter Public = new stringFilter();
  public static Agent getAvailableAgent() { return Public; };
  /** main(..) method provided to check robot, launching it
   * as standalone program. */
  public static void main(String[] args) {
  Sight.Agents.util.Pind.showConsoles();
      try {
        Request request = getDefaultRequest();
        // Now modify and assign request fields in accordance with task:
        Sight.Agents.Request submission = request.submit();
        // processing now started in separate thread:
        Result response = (Result) submission.getResult();
        // print report, verbosity level 2:
        System.out.println(response.getReport(2));
      } catch (Exception exc)
         { if (exc!=null) System.out.println(exc.getMessage());
           exc.printStackTrace();
         };
   }
;
  }