
// ISOCodeResolver.java
// Andreas Deininger
// from https://picocli.info/quick-guide.html
// Modified by Andrew Davison, ad@coe.psu.ac.th, June 2023

/* ISO code resolver with subcommands.
  
  > run ISOCodeResolver help
  Usage: ISOCodeResolver [COMMAND]
  Resolve ISO country or language codes
  Commands:
    language  Resolve ISO language code(s)
    help      Display help information about the specified command.
    country   Resolve ISO country code(s)

  > run ISOCodeResolver help country
  Usage: ISOCodeResolver country <country code>...
  Resolve ISO country code(s)
        <country code>...   a sequence of codes (e.g. cn fr th)


  Picocli features:
    * git-like subcommands
    * subcommand creation as method or class
    * help command


  Usage examples:
    > compile ISOCodeResolver.java

    > run ISOCodeResolver language de cs en sd se
    > run ISOCodeResolver country cn fr th ro no
*/

import java.util.*;

import picocli.CommandLine;
import picocli.CommandLine.*;
import picocli.CommandLine.Model.CommandSpec;


@Command(name = "ISOCodeResolver",
         subcommands = { LangSubCmd.class, 
                         HelpCommand.class },
         description = "Resolve ISO country or language codes")
public class ISOCodeResolver implements Runnable
{
  @Spec CommandSpec spec;

  @Command(name = "country",   // subcommand as method
           description = "Resolve ISO country code(s)")
  void countrySubCmd(@Parameters(arity = "1..*",
                paramLabel = "<country code>",
                description = "a sequence of codes (e.g. cn fr th)") 
                          String[] countryCodes)  // values become argument
  {
    for (String code : countryCodes)
      System.out.println( String.format("%s: %s", 
          code.toUpperCase(),
          new Locale("",code).getDisplayCountry()));
  } // end of countrySubCmd()


  public void run()
  { throw new ParameterException(spec.commandLine(), 
                                 "Specify a subcommand");
      // deal with error during command line parsing
  }


  // -----------------------------------------

  public static void main(String[] args)
  {
    int exitCode = new CommandLine(
                          new ISOCodeResolver()).execute(args);
    System.exit(exitCode);
  }

}  // end of ISOCodeResolver class


@Command(name = "language",  // subcommand as class
         description = "Resolve ISO language code(s)")
class LangSubCmd implements Runnable
{
  @Parameters(arity = "1..*", 
              paramLabel = "<language code>",
              description = "a sequence of codes (e.g. de cs en)")
  private String[] langCodes;

  public void run()
  {
    for (String code : langCodes)
      System.out.println( String.format("%s: %s", 
                    code.toLowerCase(),
                    new Locale(code).getDisplayLanguage()));
  }

}  // end of LangSubCmd class
