/* OdLib_Io - Copyright (c) 2016 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.opendocument.io;

import java.util.HashSet;
import java.util.Set;


/**
 *
 * @author Vincent Calame
 */
public class SheetNameChecker {

    private final Set<String> existingNameSet = new HashSet<String>();

    public SheetNameChecker() {

    }

    public String checkName(String name) {
        if ((name == null) || (name.length() == 0)) {
            throw new IllegalArgumentException("name is null");
        }
        name = checkNameCharacters(name);
        if (!existingNameSet.contains(name)) {
            existingNameSet.add(name);
            return name;
        }
        int p = 2;
        while (true) {
            String newName = name + " (" + p + ")";
            if (!existingNameSet.contains(newName)) {
                existingNameSet.add(newName);
                return newName;
            }
            p++;
        }
    }


    public static String checkNameCharacters(String name) {
        int length = name.length();
        StringBuilder buf = new StringBuilder(length + 10);
        for (int i = 0; i < length; i++) {
            char carac = name.charAt(i);
            switch (carac) {
                case '[':
                    carac = '(';
                    break;
                case ']':
                    carac = ')';
                    break;
                case '*':
                case ':':
                case '/':
                case '?':
                case '\\':
                    carac = '-';
                    break;
            }
            buf.append(carac);
        }
        return buf.toString();
    }

}
