package com.knecon.fforesight.service.layoutparser.processor.utils;

import lombok.experimental.UtilityClass;

@UtilityClass
public class StringDistances {


    /**
     * Calculate the Hamming distance between two strings after preprocessing to make them the same length
     * and replacing all digits with a special character '@' since they are a common occurrence in headers/footers.
     *
     * @param s1  First string
     * @param s2 Second string
     * @return The Hamming distance between the two preprocessed strings.
     */
    public int hamming(String s1, String s2) {

        int maxLength = Math.max(s1.length(), s2.length());

        String cleanFirstCandidate = padString(s1, maxLength, '\0').replaceAll("\\d", "@");
        String cleanSecondCandidate = padString(s2, maxLength, '\0').replaceAll("\\d", "@");

        int distance = 0;
        for (int i = 0; i < maxLength; i++) {
            if (cleanFirstCandidate.charAt(i) != cleanSecondCandidate.charAt(i)) {
                distance++;
            }
        }
        return distance;
    }


    private String padString(String input, int length, char padChar) {

        if (input.length() >= length) {
            return input;
        }

        StringBuilder sb = new StringBuilder(input);

        while (sb.length() < length) {
            sb.append(padChar);
        }
        return sb.toString();
    }


}
