/* UtilLib - Copyright (c) 2018 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.text;


/**
 *
 * @author Vincent Calame
 */
public final class OneDistance {

    private OneDistance() {

    }

    public static boolean apply(String left, String right) {
        int leftLength = left.length();
        int rightLength = right.length();
        if (leftLength > rightLength) {
            return apply(right, left);
        }
        int diff = rightLength - leftLength;
        switch (diff) {
            case 0:
                return substitution(left, right);
            case 1:
                return remove(left, right);
            default:
                return false;
        }
    }

    private static boolean remove(String left, String right) {
        boolean oneChance = true;
        boolean result = true;
        int leftLength = left.length();
        int rightIndex = 0;
        for (int i = 0; i < leftLength; i++) {
            char leftChar = left.charAt(i);
            char rightChar = right.charAt(rightIndex);
            if (leftChar != rightChar) {
                if (oneChance) {
                    rightIndex++;
                    rightChar = right.charAt(rightIndex);
                    if (leftChar == rightChar) {
                        oneChance = false;
                    } else {
                        result = false;
                        break;
                    }
                } else {
                    result = false;
                    break;
                }
            }
            rightIndex++;
        }
        return result;
    }

    private static boolean substitution(String left, String right) {
        boolean oneChance = true;
        boolean result = true;
        int length = left.length();
        for (int i = 0; i < length; i++) {
            char leftChar = left.charAt(i);
            char rightChar = right.charAt(i);
            if (leftChar != rightChar) {
                if (oneChance) {
                    if (i < (length - 1)) {
                        char nextLeftChar = left.charAt(i + 1);
                        char nextRightChar = right.charAt(i + 1);
                        if ((nextLeftChar == rightChar) && (nextRightChar == leftChar)) {
                            i++;
                        }
                    }
                    oneChance = false;
                } else {
                    result = false;
                    break;
                }
            }
        }
        return result;
    }

}
