/* UtilLib - Copyright (c) 2025-2026 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;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;


/**
 *
 * @author Vincent Calame
 */
public class UriStringCleaner implements StringCleaner {

    private final static Replacement apos = new Replacement("[\\u2018\\u2019]", "'");
    private final static Replacement dash = new Replacement("[_\\.,\\u00b7\\u2013]", "-");
    private final static Replacement left = new Replacement("[\\[{]", "(");
    private final static Replacement right = new Replacement("[\\]}]", ")");
    private final static Replacement word = new Replacement("[^-\\w()']", "_", Pattern.UNICODE_CHARACTER_CLASS);
    private final static Replacement multidash = new Replacement("[-]+", "-");
    private final static Replacement rightDash = new Replacement("[_][-]", "_");
    private final static Replacement leftDash = new Replacement("[-][_]", "_");
    private final static Replacement multiunderscore = new Replacement("[_]+", "_");
    private final static Replacement start = new Replacement("^[_]", "");
    private final static Replacement end = new Replacement("[_]$", "");
    private final static Replacement[] array = {apos, dash, left, right, word, multidash, rightDash, leftDash, multiunderscore, start, end};
    private final boolean withEncoding;


    public UriStringCleaner(boolean withEncoding) {
        this.withEncoding = withEncoding;
    }

    @Override
    public String clean(String s) {
        for (Replacement replacement : array) {
            s = replacement.replace(s);
        }
        if (withEncoding) {
            try {
                URI uri = new URI(s);
                return uri.toASCIIString();
            } catch (URISyntaxException e) {
                return "uri-error";
            }
        } else {
            return s;
        }
    }


    private static class Replacement {

        private final Pattern pattern;
        private final String replacement;

        private Replacement(String patternString, String replacement) {
            this.pattern = Pattern.compile(patternString);
            this.replacement = replacement;
        }

        private Replacement(String patternString, String replacement, int flag) {
            this.pattern = Pattern.compile(patternString, flag);
            this.replacement = replacement;
        }

        private String replace(String text) {
            String result = pattern.matcher(text).replaceAll(replacement);
            return result;
        }


    }

}
