/* FichothequeLib_Tools - Copyright (c) 2014-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.fichotheque.tools.thesaurus;

import java.util.Collection;
import java.util.List;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.thesaurus.ThesaurusEditor;


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

    private final ThesaurusEditor thesaurusEditor;

    public ChildrenReorderEngine(ThesaurusEditor thesaurusEditor) {
        this.thesaurusEditor = thesaurusEditor;
    }

    public void reorder(Motcle motcle, Collection<Motcle> newOrder) {
        List<Motcle> currentChildren = (motcle != null) ? motcle.getChildList() : thesaurusEditor.getThesaurus().getFirstLevelList();
        int size = currentChildren.size();
        if (size == 0) {
            return;
        }
        if (size == 1) {
            return;
        }
        int p = 0;
        for (Motcle child : newOrder) {
            if (isParent(motcle, child)) {
                thesaurusEditor.setChildIndex(child, p);
                p++;
            }
        }
    }

    private boolean isParent(Motcle parent, Motcle child) {
        if (parent == null) {
            if (child.getParent() != null) {
                return false;
            } else {
                return child.getThesaurus().equals(thesaurusEditor.getThesaurus());
            }
        } else {
            Motcle otherParent = child.getParent();
            if (otherParent == null) {
                return false;
            } else {
                return otherParent.equals(parent);
            }
        }
    }

}
