/* BdfServer - Copyright (c) 2009-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 fr.exemole.bdfserver.tools.ficheform.builders;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.exportation.table.FicheTableParameters;
import fr.exemole.bdfserver.api.ficheform.FicheFormParameters;
import fr.exemole.bdfserver.api.ficheform.include.CorpusEntry;
import fr.exemole.bdfserver.api.ficheform.include.SubsetItemValue;
import fr.exemole.bdfserver.api.ui.IncludeUi;
import fr.exemole.bdfserver.api.ui.SubsetIncludeUi;
import fr.exemole.bdfserver.api.ui.UiComponent;
import fr.exemole.bdfserver.tools.L10nUtils;
import fr.exemole.bdfserver.tools.exportation.table.BdfTableExportUtils;
import fr.exemole.bdfserver.tools.exportation.table.DefaultTableDefFactory;
import fr.exemole.bdfserver.tools.ficheform.FicheFormUtils;
import fr.exemole.bdfserver.tools.ui.UiUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.corpus.FicheMeta;
import net.fichotheque.junction.Liaison;
import net.fichotheque.exportation.table.CellConverter;
import net.fichotheque.exportation.table.SubsetTable;
import net.fichotheque.exportation.table.TableDef;
import net.fichotheque.include.ExtendedIncludeKey;
import net.fichotheque.pointeurs.FichePointeur;
import net.fichotheque.pointeurs.SubsetItemPointeur;
import net.fichotheque.tools.exportation.table.SubsetTableBuilder;
import net.mapeadores.util.annotation.Nullable;
import net.mapeadores.util.attr.AttributeUtils;
import net.mapeadores.util.attr.Attributes;


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

    private final static String CHECK_TYPE = "check";
    private final static String TABLE_TYPE = "table";
    private final String name;
    private final Corpus corpus;
    private final List<SubsetItemValue> valueList = new ArrayList<SubsetItemValue>();
    private String type = CHECK_TYPE;
    private String label = "";
    private boolean mandatory = false;
    private boolean hasWeightFilter = false;
    private Attributes attributes = AttributeUtils.EMPTY_ATTRIBUTES;
    private SubsetTable subsetTable;
    private CellConverter cellConverter;

    public CorpusEntryBuilder(String name, Corpus corpus) {
        this.name = name;
        this.corpus = corpus;
    }

    public CorpusEntryBuilder setHasWeightFilter(boolean hasWeightFilter) {
        this.hasWeightFilter = hasWeightFilter;
        return this;
    }

    public CorpusEntryBuilder setLabel(String label) {
        if (label == null) {
            throw new IllegalArgumentException("label is null");
        }
        this.label = label;
        return this;
    }

    public CorpusEntryBuilder setMandatory(boolean mandatory) {
        this.mandatory = mandatory;
        return this;
    }

    public CorpusEntryBuilder setAttributes(Attributes attributes) {
        if (attributes == null) {
            this.attributes = AttributeUtils.EMPTY_ATTRIBUTES;
        } else {
            this.attributes = attributes;
        }
        return this;
    }

    public CorpusEntryBuilder setTableInfos(SubsetTable subsetTable, CellConverter cellConverter) {
        if ((subsetTable == null) || (cellConverter == null)) {
            type = CHECK_TYPE;
            this.subsetTable = null;
            this.cellConverter = null;
        } else {
            type = TABLE_TYPE;
            this.subsetTable = subsetTable;
            this.cellConverter = cellConverter;
        }
        return this;
    }

    public CorpusEntryBuilder addFicheMeta(FicheMeta ficheMeta, int weight) {
        String value = String.valueOf(ficheMeta.getId());
        if (weight > 1) {
            value = value + "<" + weight + ">";
        }
        valueList.add(FicheFormUtils.toSubsetItemValue(value, weight, ficheMeta));
        return this;
    }

    public CorpusEntryBuilder populateOptions(FicheFormParameters ficheFormParameters, IncludeUi includeUi) {
        return this
                .setLabel(L10nUtils.toLabelString(ficheFormParameters, includeUi))
                .setMandatory(includeUi.isMandatory())
                .setAttributes(includeUi.getAttributes());
    }

    public CorpusEntry toCorpusEntry() {
        List<SubsetItemValue> finalList = FicheFormUtils.wrap(valueList.toArray(new SubsetItemValue[valueList.size()]));
        if (type.equals(TABLE_TYPE)) {
            return new InternalTableCorpusEntry(name, corpus, label, mandatory, attributes, finalList, subsetTable, cellConverter);
        } else {
            return new InternalCheckCorpusEntry(name, corpus, hasWeightFilter, label, mandatory, attributes, finalList);
        }
    }

    @Nullable
    public static CorpusEntryBuilder check(FichePointeur fichePointeur, FicheFormParameters ficheFormParameters, SubsetIncludeUi includeUi) {
        Corpus corpus = (Corpus) ficheFormParameters.getBdfServer().getFichotheque().getSubset(includeUi.getSubsetKey());
        if (corpus == null) {
            return null;
        }
        ExtendedIncludeKey includeKey = includeUi.getExtendedIncludeKey();
        SubsetItemPointeur pointeur = FicheFormUtils.checkMasterPointeur(fichePointeur, ficheFormParameters, includeUi);
        CorpusEntryBuilder builder = CorpusEntryBuilder.init(includeUi.getName(), corpus)
                .setHasWeightFilter(includeKey.hasWeightFilter());
        populate(builder, corpus, pointeur, includeKey);
        if ((builder.valueList.isEmpty()) && (includeUi.isObsolete())) {
            return null;
        }
        builder
                .populateOptions(ficheFormParameters, includeUi);
        if (includeUi.isFicheTable()) {
            BdfServer bdfServer = ficheFormParameters.getBdfServer();
            List<UiComponent> uiComponentList = UiUtils.filterFicheTableUiComponents(bdfServer.getUiManager().getMainUiComponents(corpus), fichePointeur.getSubsetKey());
            TableDef tableDef = DefaultTableDefFactory.fromComponentList(bdfServer, corpus, uiComponentList, FicheTableParameters.LABEL_PATTERNMODE, ficheFormParameters.getPermissionSummary());
            SubsetTable subsetTable = SubsetTableBuilder.init(corpus).populate(tableDef, bdfServer.getTableExportContext()).toSubsetTable();
            builder.setTableInfos(subsetTable, BdfTableExportUtils.toCellConverter(bdfServer, ficheFormParameters.getDefaultExtractionContext(), subsetTable));
        }
        return builder;
    }

    private static void populate(CorpusEntryBuilder builder, Corpus corpus, SubsetItemPointeur pointeur, ExtendedIncludeKey includeKey) {
        Collection<Liaison> liaisons = pointeur.getLiaisons(corpus, includeKey);
        if (includeKey.hasWeightFilter()) {
            for (Liaison liaison : liaisons) {
                builder.addFicheMeta((FicheMeta) liaison.getSubsetItem(), -1);
            }
        } else {
            for (Liaison liaison : liaisons) {
                builder.addFicheMeta((FicheMeta) liaison.getSubsetItem(), liaison.getTie().getWeight());
            }
        }
    }

    public static CorpusEntryBuilder init(String name, Corpus corpus) {
        return new CorpusEntryBuilder(name, corpus);
    }


    private static class InternalCheckCorpusEntry implements CorpusEntry.Check {

        private final String name;
        private final Corpus corpus;
        private final boolean withWeightFilter;
        private final String label;
        private final boolean mandatory;
        private final Attributes attributes;
        private final List<SubsetItemValue> valueList;

        private InternalCheckCorpusEntry(String name, Corpus corpus, boolean withWeightFilter, String label, boolean mandatory, Attributes attributes, List<SubsetItemValue> valueList) {
            this.name = name;
            this.withWeightFilter = withWeightFilter;
            this.corpus = corpus;
            this.label = label;
            this.mandatory = mandatory;
            this.attributes = attributes;
            this.valueList = valueList;
        }

        @Override
        public String getIncludeName() {
            return name;
        }

        @Override
        public Corpus getCorpus() {
            return corpus;
        }

        @Override
        public boolean hasWeightFilter() {
            return withWeightFilter;
        }

        @Override
        public String getLabel() {
            return label;
        }

        @Override
        public boolean isMandatory() {
            return mandatory;
        }

        @Override
        public Attributes getAttributes() {
            return attributes;
        }

        @Override
        public List<SubsetItemValue> getValueList() {
            return valueList;
        }

    }


    private static class InternalTableCorpusEntry implements CorpusEntry.Table {

        private final String name;
        private final Corpus corpus;
        private final String label;
        private final boolean mandatory;
        private final Attributes attributes;
        private final List<SubsetItemValue> valueList;
        private final SubsetTable subsetTable;
        private final CellConverter cellConverter;


        private InternalTableCorpusEntry(String name, Corpus corpus, String label, boolean mandatory, Attributes attributes, List<SubsetItemValue> valueList, SubsetTable subsetTable, CellConverter cellConverter) {
            this.name = name;
            this.corpus = corpus;
            this.label = label;
            this.mandatory = mandatory;
            this.attributes = attributes;
            this.valueList = valueList;
            this.subsetTable = subsetTable;
            this.cellConverter = cellConverter;
        }

        @Override
        public String getIncludeName() {
            return name;
        }

        @Override
        public Corpus getCorpus() {
            return corpus;
        }

        @Override
        public String getLabel() {
            return label;
        }

        @Override
        public boolean isMandatory() {
            return mandatory;
        }

        @Override
        public Attributes getAttributes() {
            return attributes;
        }

        @Override
        public List<SubsetItemValue> getValueList() {
            return valueList;
        }

        @Override
        public SubsetTable getSubsetTable() {
            return subsetTable;
        }

        @Override
        public CellConverter getCellConverter() {
            return cellConverter;
        }

    }

}
