/* FichothequeLib_Tools - Copyright (c) 2015-2025 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.junction;

import java.text.ParseException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Predicate;
import net.fichotheque.Fichotheque;
import net.fichotheque.Subset;
import net.fichotheque.SubsetItem;
import net.fichotheque.include.IncludeKey;
import net.fichotheque.junction.JunctionChanges;


/**
 *
 * @author Vincent Calame
 */
public final class JunctionRemoveParser {

    private JunctionRemoveParser() {

    }

    public static JunctionChanges parseRemove(String[] values, Fichotheque fichotheque, Predicate<SubsetItem> predicate) {
        Map<SubsetItem, JunctionChangeBuilder> map = new LinkedHashMap<SubsetItem, JunctionChangeBuilder>();
        for (String value : values) {
            int idx = value.indexOf('/');
            if (idx > 0) {
                try {
                    IncludeKey includeKey = IncludeKey.parse(value.substring(0, idx));
                    int id = Integer.parseInt(value.substring(idx + 1));
                    Subset subset = fichotheque.getSubset(includeKey.getSubsetKey());
                    if (subset != null) {
                        SubsetItem subsetItem = subset.getSubsetItemById(id);
                        if (subsetItem != null) {
                            if ((predicate != null) && (!predicate.test(subsetItem))) {
                                continue;
                            }
                            JunctionChangeBuilder builder = map.get(subsetItem);
                            if (builder == null) {
                                builder = new JunctionChangeBuilder();
                                map.put(subsetItem, builder);
                            }
                            builder.addRemovedMode(includeKey.getMode());
                        }
                    }
                } catch (ParseException | NumberFormatException e) {

                }
            }
        }
        JunctionChangesBuilder junctionChangesBuilder = new JunctionChangesBuilder();
        for (Map.Entry<SubsetItem, JunctionChangeBuilder> entry : map.entrySet()) {
            junctionChangesBuilder.addEntry(entry.getKey(), entry.getValue().toJunctionChange());
        }
        return junctionChangesBuilder.toJunctionChanges();
    }

}
