001package jmri.jmrit.symbolicprog;
002
003import jmri.util.AlphanumComparator;
004
005/*
006 * Compare CV names.
007 * <p>
008 * <ul>
009 * <li>Groups are separated by periods. If there are 
010 *     different numbers of groups, more is later
011 * <li>Each group is ordered, left group first, by an AlphanumComparator
012 *
013 */
014public class CVNameComparator extends AlphanumComparator {
015
016    @Override
017    public int compare(String s1, String s2) {
018        if (s1.indexOf('.')>=0 || s2.indexOf('.')>=0) {
019            String ts1 = s1;
020            String ts2 = s2;
021            while (!ts1.isEmpty() && !ts2.isEmpty() ) {
022                int index1 = ts1.indexOf('.');
023                int index2 = ts2.indexOf('.');
024
025                // depending on how many dots:
026                if (index1<0 && index2<0) return super.compare(ts1, ts2);
027                if (index1<0) return -1;
028                if (index2<0) return +1;
029
030                // now extract chunks
031                String c1 = "";
032                if (index1 > 0) {
033                    c1 = ts1.substring(0, index1);
034                    ts1 = ts1.substring(index1+1, ts1.length());
035                } else {
036                    c1 = ts1;
037                    ts1 = "";
038                }
039
040                String c2 = "";
041                if (index2 > 0) {
042                    c2 = ts2.substring(0, index2);
043                    ts2 = ts2.substring(index2+1, ts2.length());
044                } else {
045                    c2 = ts2;
046                    ts2 = "";
047                }
048
049                if (c1.isEmpty() && c2.isEmpty()) return 0;
050                if (c1.isEmpty()) return +1;
051                if (c2.isEmpty()) return -1;
052                
053                int retval = super.compare(c1, c2);
054                if (retval != 0) return retval;
055            }
056        }
057        return super.compare(s1, s2);
058    }
059}