package org.teiid.core.util;

/**
 * A class to hold name utility.
 *
 * @author Roman Pedchenko
 * @date 2017.02.14
 */
public class NamesUtil {

    public static String getCanonicalName(String name) {
        if (name == null)
            return null;
        name = splitAndStripBrackets(name);
        int size = name.length();
        if (size == 0)
            return name;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++)
            sb.append(Character.toUpperCase(name.charAt(i)));
        return sb.toString();
    }

    public static String getCanonicalNamePreservingCase(String name) {
        if (name == null)
            return null;
        return splitAndStripBrackets(name);
    }

    private static String splitAndStripBrackets(String name) {
        String[] split = name.split("\\.");
        for (int ix = 0; ix < split.length; ix++) {
            split[ix] = stripBrackets(split[ix]);
        }
        return String.join(".", split);
    }

    private static String stripBrackets(String name) {
        while (name.startsWith("[") && name.endsWith("]")) {
            name = name.substring(1, name.length() - 1);
        }
        return name;
    }

    public static String addBrackets(String name) {
        if (name == null) return null;
        String[] split = name.split("\\.");
        for (int ix = 0; ix < split.length; ix++) {
            split[ix] = wrap(stripBrackets(split[ix]));
        }
        return String.join(".", split);
    }

    public static String cleanNameForColumn(String columName, boolean allowsSpecialChars, boolean allowsStartWithDigit, boolean allowMultipleUnderscoresInColumnNames) {
        String cleanColumnName = columName;
        if (!allowsStartWithDigit) {
            cleanColumnName = cleanColumnName.replaceAll("^[^\\p{L}]", "_");
        }
        String regexToReplaceAll = null;
        if (allowMultipleUnderscoresInColumnNames) {
            regexToReplaceAll = allowsSpecialChars ? "[^\\p{L}\\p{N}_ \\-()*]+" : "[^\\p{L}\\p{N}_]+";
        } else {
            regexToReplaceAll = allowsSpecialChars ? "[^\\p{L}\\p{N} \\-()*]+" : "[^\\p{L}\\p{N}]+";
        }
        cleanColumnName = cleanColumnName.replaceAll(regexToReplaceAll, "_");
        return cleanColumnName;
    }

    public static String wrap(String name) {
        return "[" + name + "]";
    }

}
