package hw4;

/**
 * A PolySounder object can be used to find words that sound alike.
 *
 * @author P. Parrot, Lexicality, Inc.
 * @version 1.0
 */
public class PolySounder {

    private int length;
    private int side;

    /**
     * Explicit Value Constructor.
     *
     * @param length The length of the code to produce from the word
     * @param side The side to pad on (SwingConstants.LEFT or .RIGHT)
     */
    public PolySounder(int length, int side) {
        this.length = length;
        this.side = side;
    }


    /**
     * Create a code that is a summary of the pronunciation of a word.
     *
     * @param word The word to create the code for
     * @return The code
     */
    public String toCode(String word) {
        char c;
        String alphabetic;
        String codedConsonants;
        String noDups;
        String noHW;
        String noVowels;
        String result;
        String s;

        // Convert to uppercase
        s = word.toUpperCase();
        System.out.println("\n" + s);

        // Remove non alphabetic characters
        alphabetic = "";
        for (int i = 0; i < s.length(); i++) {
            c = s.charAt(i);
            if ((c >= 'A') && (c <= 'Z')) {
                alphabetic += c;
            }
        }

        // Remove the vowels
        noVowels = TextUtils.removeFrom(alphabetic, new char[]{'A', 'E', 'I', 'O', 'U'});

        // Remove H and W
        noHW = TextUtils.removeFrom(noVowels, new char[]{'H', 'W'});

        // Code the consonants
        char[] consonants = new char[]{'B', 'F', 'P', 'V', 'C', 'G', 'J', 'K', 'Q', 'S', 'X', 
            'Z', 'D', 'T', 'L', 'M', 'N', 'R'};
        char[] codes      = new char[]{'1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', 
            '2', '3', '3', '4', '5', '5', '6'};
        codedConsonants = "";
        for (int i = 0; i < noHW.length(); i++) {
            c = noHW.charAt(i);
            codedConsonants += TextUtils.findReplacementFor(c, consonants, codes);
        }

        // Remove duplicates
        noDups = "" + codedConsonants.charAt(0);
        for (int i = 1; i < codedConsonants.length() - 1; i++) {
            c = codedConsonants.charAt(i);
            if (c != codedConsonants.charAt(i - 1)) {
                noDups += c; 
            }
        }

        result = TextUtils.pad(noDups,  '0', side, length);

        return result;
    }
}
