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

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.fichotheque.Fichotheque;
import net.fichotheque.Subset;
import net.fichotheque.include.IconSources;
import net.fichotheque.include.IncludeKey;
import net.fichotheque.include.IncludeMode;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.utils.ThesaurusUtils;
import net.mapeadores.util.attr.Attribute;


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

    private IconSourcesParser() {

    }

    public static IconSources parse(Fichotheque fichotheque, Attribute attribute) {
        List<InternalEntry> entryList = new ArrayList<InternalEntry>();
        Set<IncludeKey> doneSet = new HashSet<IncludeKey>();
        for (String value : attribute) {
            try {
                IncludeKey includeKey = IncludeKey.parse(value);
                if (!doneSet.contains(includeKey)) {
                    doneSet.add(includeKey);
                    Subset subset = fichotheque.getSubset(includeKey.getSubsetKey());
                    if ((subset != null) && (subset instanceof Thesaurus)) {
                        entryList.add(new InternalEntry((Thesaurus) subset, includeKey));
                    }
                }
            } catch (ParseException pe) {

            }
        }
        return new InternalIconSources(ThesaurusUtils.wrap(entryList.toArray(new IconSources.Entry[entryList.size()])));
    }


    private static class InternalEntry implements IconSources.Entry {

        private final Thesaurus thesaurus;
        private final IncludeMode includeMode;

        private InternalEntry(Thesaurus thesaurus, IncludeMode includeMode) {
            this.thesaurus = thesaurus;
            this.includeMode = includeMode;
        }

        @Override
        public Thesaurus getThesaurus() {
            return thesaurus;
        }

        @Override
        public IncludeMode getIncludeMode() {
            return includeMode;
        }

    }


    private static class InternalIconSources implements IconSources {

        private final List<IconSources.Entry> entryList;

        private InternalIconSources(List<IconSources.Entry> entryList) {
            this.entryList = entryList;
        }

        @Override
        public List<IconSources.Entry> getEntryList() {
            return entryList;
        }

    }

}
