package oracle.forms.fd;

import java.util.regex.*;
import oracle.forms.handler.IHandler;
import oracle.forms.ui.VBean;
import oracle.forms.properties.ID;
import oracle.forms.ui.CustomEvent;

  /**
   * A Bean to handle regular expression
   *
   * @author Francois Degrelle
   * @version 1.0
   * 
   * need the Sun Java Plugin
   */
   
public class RegularExp extends VBean
{
  // variables
  public final static ID setProp    = ID.registerProperty("SET");        
  public final static ID setModel   = ID.registerProperty("SET_PATTERN");    
  public final static ID setString  = ID.registerProperty("SET_STRING");      
  public final static ID getString  = ID.registerProperty("GET_STRING");  
  public final static ID getResult  = ID.registerProperty("GET_RESULT");  
  public final static ID getGroup   = ID.registerProperty("GET_GROUP");    
  public final static ID getPos     = ID.registerProperty("GET_POS");    
  private IHandler    m_handler;  
  private String sPattern = "" ;
  private Pattern pattern;
  private Matcher matcher;
  private String sGroup="";
  private String sModel="", sString="" ;
  private int    iStart=0, iEnd = 0 ;
      
  public void init(IHandler handler)
  {
    m_handler = handler;
    super.init(handler);
  }  
  
  /*
   *  Set some properties 
   */
  public boolean setProperty(ID property, Object value)
  {
    // the pattern
    if( property == setModel )
    {
      sModel = value.toString() ;
      return true ;
    }
    // the string to compare
    else if( property == setString )
    {
      sString = value.toString() ;
      return true ;
    }
    else
    {
     return super.setProperty(property, value);
    }
  }  

  /*
   * Get the properties
   */
   public Object getProperty(ID pId) // Get the current pressed button ID
   {
    
     // get the boolean result
     if (pId == getResult)
     {
       return "" + bMatch(sModel, sString);
     }
     // get the corresponding group
     else if (pId == getGroup)
     {
       return "" + sGroup ;
     }     
     // get the start and end position in the string
     else if (pId == getPos)
     {
       if( iStart > -1 )
         return "" + iStart + "," + iEnd ;
      else
         return "" ;
     }
     
     else
     {
       return super.getProperty(pId);
     }
    
   } 

  // main method
  public boolean bMatch(String p_pattern, String p_string)
  {
    pattern = Pattern.compile(p_pattern);
    matcher = pattern.matcher(p_string);
    if(matcher.find()) {
       sGroup = matcher.group() ;
       iStart = matcher.start() ;
       iEnd   = matcher.end() ;
      return true;
    }
    else 
    {
      sGroup = "" ;
      iStart = -1 ;
      iEnd   = -1 ;
      return false ;
    }
  }


}
