package ipipan.poliqarp.stat;

import java.text.Collator;
import java.util.Comparator;

public class MatchCountComparator implements Comparator<MatchCount> {
   static final int AFRONTE = 1;
   static final int ATERGO  = 2;
   static final int BY_FREQ = 3;
   static final int CTEST   = 4;

   int order = 0;
   CTest ctest = null;
   Collator collator;
   String testName;

   int getOrder(String sortby) {
      if (sortby.equalsIgnoreCase("by freq"))
         return BY_FREQ;

      if (sortby.equalsIgnoreCase("a fronte"))
         return AFRONTE;

      if (sortby.equalsIgnoreCase("a tergo"))
         return ATERGO;

      if (sortby.startsWith("by ")) {
         testName = sortby.substring(3);
         ctest = new CTest(testName);
         return CTEST;
      }

      return 0;
   }

   public MatchCountComparator(int o) {
      order = o;
      collator = Collator.getInstance();
   }

   public MatchCountComparator(String sortby) {
      order = getOrder(sortby.trim());
      collator = Collator.getInstance();
   }

   public int compare(MatchCount a1, MatchCount a2) {
      if (a1 == null && a2 == null) return 0;
      if (a1 == null) return 1;
      if (a2 == null) return -1;

      switch (order) {

         case BY_FREQ:
            if (a1.getCount() < a2.getCount()) return 1;
            if (a1.getCount() > a2.getCount()) return -1;
            return 0;

         case AFRONTE:
            return collator.compare(a1.getMatch(), a2.getMatch());

         case CTEST:
            float c1 = a1.getCp(ctest), c2 = a2.getCp(ctest);
            if (c1 < c2) return  1;
            if (c1 > c2) return -1;
            return 0;

         default:
            return 0;
      }
   }

   public String getTestName() {
      if (order != CTEST)
         return "";
      return testName;
   }
}

