package com.wrox.algorithms.wmatch;

public final class SoundexPhoneticEncoder implements PhoneticEncoder {
    /** pojedyncza instancja klasy (singleton) */
    public static final SoundexPhoneticEncoder INSTANCE = new SoundexPhoneticEncoder();

        private static final char[] CHARACTER_MAP = 
            "01230120022455012623010202".toCharArray();
         /** ABCDEFGHIJKLMNOPQRSTUVWXYZ */ 

    private SoundexPhoneticEncoder() {
    }

    public String encode(CharSequence string) {
        assert string != null : "nie określono tekstu źródłowego";
        assert string.length() > 0 : "tekst źródłowy jest pusty";

        char[] result = {'0', '0', '0', '0'};

        result[0] = Character.toUpperCase(string.charAt(0));

        int stringIndex = 1;
        int resultIndex = 1;

        while (stringIndex < string.length() && resultIndex < result.length) {
            char c = map(string.charAt(stringIndex));

            if (c != '0' && c != result[resultIndex - 1]) {
                result[resultIndex] = c;
                ++resultIndex;
            }

            ++stringIndex;
        }

        return String.valueOf(result);
    }

    /**
     * Odwzorowanie pojedynczego znaku w jego wartość kodową Soundex
     */
    private static char map(char c) {
        int index = Character.toUpperCase(c) - 'A';
        return isValid(index) ? CHARACTER_MAP[index] : '0';
    }

    
    private static boolean isValid(int index) {
        return index >= 0 && index < CHARACTER_MAP.length;
    }
}
