/* UtilLib - Copyright (c) 2007-2017 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.collation.group;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;


/**
 *
 * @author Vincent Calame
 */
class DefaultCollationGroup implements CollationGroup {

    private final char initial;
    private final SortedMap<String, Object> sortedMap = new TreeMap<String, Object>();

    DefaultCollationGroup(char initial) {
        this.initial = initial;
    }

    @Override
    public char getInitial() {
        return initial;
    }

    @Override
    public List<ObjectWrapper> getSortedObjectWrapperList() {
        List<ObjectWrapper> result = new ArrayList<ObjectWrapper>();
        for (Object obj : sortedMap.values()) {
            if (obj instanceof List) {
                List<ObjectWrapper> currentList = (List<ObjectWrapper>) obj;
                result.addAll(currentList);
            } else {
                result.add((ObjectWrapper) obj);
            }
        }
        return result;
    }

    boolean isEmpty() {
        return sortedMap.isEmpty();
    }

    void addObject(String collationKey, ObjectWrapper objectWrapper) {
        Object obj = sortedMap.get(collationKey);
        if (obj == null) {
            sortedMap.put(collationKey, objectWrapper);
        } else if (obj instanceof List) {
            List<ObjectWrapper> currentList = (List<ObjectWrapper>) obj;
            addInList(currentList, objectWrapper);
        } else {
            List<ObjectWrapper> arrayList = new ArrayList<ObjectWrapper>();
            arrayList.add((ObjectWrapper) obj);
            addInList(arrayList, objectWrapper);
            sortedMap.put(collationKey, arrayList);
        }
    }

    private void addInList(List<ObjectWrapper> list, ObjectWrapper objectWrapper) {
        int size = list.size();
        String sourceString = objectWrapper.getSourceString();
        boolean done = false;
        for (int i = 0; i < size; i++) {
            ObjectWrapper obj2 = (ObjectWrapper) list.get(i);
            if (obj2.getSourceString().compareTo(sourceString) > 0) {
                list.add(i, objectWrapper);
                done = true;
                break;
            }
        }
        if (!done) {
            list.add(objectWrapper);
        }
    }

}
