package ca.janeg.cb;

import java.util.Comparator;

/**
 *  Compares fully qualified class, constructor, field and method
 *  names based on their simple name; ignores character case.
 *
 *  @author     Jane Griscti jane@janeg.ca
 *  @created    January 13, 2002
 */

class NameComparator implements Comparator {

    private final static NameComparator INSTANCE  = new NameComparator();


    /*
     *  Ensure only one NameComparator is created (Singleton)
     */
    private NameComparator() { }


    private String getDelimiter( final String str ) {
        String delimiter  = "";
        if( str.indexOf( "/" ) > 0 ) {
            delimiter = "/";
        } else if( str.indexOf( "." ) > 0 ) {
            delimiter = ".";
        }

        return delimiter;
    }


    private String extract( final String str, final String delimiter ) {
        String result  = str;

        // drop any parameters if it's a method or constructor name
        if( str.indexOf( "(" ) > 0 ) {
            result = str.substring( 0, str.indexOf( "(" ) );
        }

        if( delimiter != "" ) {
            int index  = result.lastIndexOf( delimiter );
            result = result.substring( index + 1 );
        }

        return result;
    }


    /**
     *  Returns a singleton instance of NameComparator
     *
     *@return    a NameComparator object
     */
    public static NameComparator getInstance() {
        return INSTANCE;
    }


    /**
     *  Compares two objects
     *
     *@param  o1  the first object being compared
     *@param  o2  the second object being compared
     *@return     a negative integer, zero, or a positive integer as the first
     *      argument is less than, equal to, or greater than the second.
     */
    public int compare( final Object o1, final Object o2 ) {
        String s1           = o1.toString();
        String s2           = o2.toString();

        String s1Delimiter  = getDelimiter( s1 );
        String s2Delimiter  = getDelimiter( s2 );

        s1 = extract( o1.toString(), s1Delimiter );
        s2 = extract( o2.toString(), s2Delimiter );

        return s1.compareToIgnoreCase( s2 );
    }
}