package org.mockejb.interceptor;


import org.apache.oro.text.regex.*;

/**
 * Helper class used to isolate pointcuts that use regexp from the 
 * concrete regexp API. Currently we use Jakarta ORO but may 
 * switch to the java regexp package in the future
 * 
 * @author Alexander Ananiev
 */
class RegexpWrapper {
    
    private Pattern pattern;
    private String patternString;

    private PatternCompiler compiler = new Perl5Compiler();;
    private PatternMatcher matcher = new Perl5Matcher(); 
    
    public RegexpWrapper( final String patternString ){
        this.patternString = patternString;
        try {
            pattern = compiler.compile( patternString );
        }
        catch( MalformedPatternException mpe ) {
            throw new PointcutException( mpe.getMessage(), mpe);
        }
        
    }

    /**
     * Tests if this regexp pattern is contained by the given string.
     * @param stringToMatch string where to search for the occurences of this regexp
     * @return true if the string contains the patternprovided method should be intercepted
     */
    public boolean containedInString( String stringToMatch ) {

        return matcher.contains( stringToMatch, pattern );        
        
    }
    
    
    /**
     * Returns true if the given object is of the same type and 
     * it has the same pattern.
     */
    public boolean equals( Object obj ){
        if ( ! (obj instanceof RegexpWrapper) )
            return false;
        
        RegexpWrapper regexpWrapper = (RegexpWrapper ) obj;
        
        return ( patternString.equals( regexpWrapper.patternString ));
    }
    
    public int hashCode() {
        int result = 17;
        result = 37*result+patternString.hashCode();
        
        return result;
    }

}