
// CSVQuery.java
// Andrew Davison, ad@coe.psu.ac.th, Nov. 2022

/* List all the cities in Thailand with populations
   over 100,000. Uses worldcities.csv which has a 
   header line.

   The (city, population) CSV data is stored in a list of
   Pair objects, which is sorted into descending order by
   population before it is printed.

    Usage:
      > compile CSVQuery.java
      > run CSVQuery 

*/

import java.io.*;
import java.util.*;

import org.apache.commons.csv.*;


public class CSVQuery 
{
  public static void main(String[] args)
  {
    try {
      Reader in = new FileReader("worldcities.csv");

      CSVFormat.Builder builder = CSVFormat.DEFAULT.builder();
      CSVFormat format = builder.setHeader().
                           setSkipHeaderRecord(true).
                           setIgnoreHeaderCase(true).
                           setTrim(true).build();

      CSVParser parser = new CSVParser(in, format);

      // System.out.println( parser.getHeaderNames());
      
      ArrayList<Pair<String,Integer>> cityPops = new ArrayList<>();

      // store (city,pop) in Pair object if pop > 100,000
      for (CSVRecord record : parser) {
        if (record.get("country").equals("Thailand")) {
          int pop = getInteger(record.get("population"));
          if (pop > 100000) {
            // System.out.println(record.get("City") + ": " + pop);
            Pair<String,Integer> p = new Pair<>(record.get("City"), pop);
            cityPops.add(p);
          }
        }
      }

      Collections.sort(cityPops, new Comparator<Pair<String,Integer>>() {
        public int compare(Pair<String,Integer> p1,
                           Pair<String,Integer> p2) 
        // sort into descending order by populations
        { return p1.getSecond() > p2.getSecond() ? -1 : 
                    p1.getSecond() < p2.getSecond() ? 1 : 0;   }
      });

      // print out the sorted list
      for (Pair<String,Integer> p : cityPops)
        System.out.println(p.getFirst() + ": " + p.getSecond());
    }
    catch(IOException e)
    { System.out.println(e);  }
  }  // end of main()


  private static int getInteger(String s)
  {
    int i = 0;  // a default value
    try {
      i = Integer.parseInt(s);
    }
    catch(NumberFormatException e) {}
    return i;
  }

} // end of CSVQuery class