
// HunspellTest.java
// Andrew Davison, ad@coe.psu.ac.th, Dec. 2022

/* Using Ole Schönburg's hunspell-java,
   Java bindings to Hunspell
   https://gitlab.com/dumonts/hunspell-java

   It includes the Hunspell library, but not dictionaries.
   https://hunspell.github.io/

   JARs available at:
   https://jar-download.com/artifact-search/hunspell

  Usage:
    > compile HunspellTest.java
    > run HunspellText <word>
    e.g.
    > run HunspellText dogg
    > run HunspellText bankruptcpy

*/

import java.io.*;
import java.nio.file.*;
import java.util.*;

import dumonts.hunspell.Hunspell;


public class HunspellTest
{
  private static final String DICT = "dicts/en_US.dic";
  private static final String DICT_TREE = "dicts/en_US.aff";
   /* From:
 https://sourceforge.net/projects/wordlist/files/speller/2020.12.07/
   */


  public static void main(String args[])
  {
    if (args.length != 1) {
      System.out.println("Usage: run HunspellText <word>");
      System.exit(0);
    }
    String word = args[0];

    Hunspell hs = new Hunspell(Paths.get(DICT), Paths.get(DICT_TREE));

    boolean isCorrect = hs.spell(word);
    System.out.println("Is " + word + " correctly spelt? " + isCorrect);

    if (!isCorrect) {
      // generate and print some suggested changes
      String[] suggestions = hs.suggest(word);
      System.out.println("Suggestions (" + suggestions.length + "):");
      for (int i=0; i < suggestions.length; i++) 
        System.out.println((i+1) + ". " + suggestions[i]);

      if (yesNo("Add " + word + " to library?")) {
        hs.add(word);   // only added to this instance, not to dictionary
                        // so a bit pointless in this code
        System.out.println("Is " + word + " recognized? " + hs.spell(word));
      }
    }
    hs.close();
  }  // end of main()



  private static boolean yesNo(String query)
  // return a boolean denoting the user's answer to the query
  {
    try (Scanner sc = new Scanner(System.in)) {
      System.out.print(query + " ");
      while (true) {
        String line = sc.nextLine().trim().toLowerCase();
        char ch = line.charAt(0);
        if (ch == 'n')
          return false;
        else if (ch == 'y')
          return true;
        System.out.print("Try again: ");
      }
    }
  }  // end of yesNo()

}  // end of HunspellTest class


