/* BdfServer_HtmlProducers - Copyright (c) 2010-2023 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.htmlproducers.edition;

import fr.exemole.bdfserver.api.instruction.BdfParameters;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.interaction.InteractionConstants;
import fr.exemole.bdfserver.api.interaction.domains.EditionDomain;
import net.fichotheque.permission.PermissionSummary;
import fr.exemole.bdfserver.html.BdfHtmlUtils;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.html.ParameterMap;
import fr.exemole.bdfserver.html.consumers.Button;
import fr.exemole.bdfserver.html.consumers.PageUnit;
import fr.exemole.bdfserver.tools.BdfServerUtils;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import net.fichotheque.Subset;
import net.fichotheque.SubsetItem;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.corpus.FicheMeta;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.utils.CorpusMetadataUtils;
import net.fichotheque.utils.FichothequeUtils;
import net.fichotheque.utils.ThesaurusUtils;
import net.mapeadores.util.html.HtmlAttributes;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.localisation.Litteral;
import net.mapeadores.util.logging.LogUtils;


/**
 *
 * @author Vincent Calame
 */
public class SatelliteFicheCreationHtmlProducer extends BdfServerHtmlProducer {

    private final static Button NEW_BUTTON = Button.submit("action-FicheCreate", "_ label.edition.satellite_creation");
    private final PermissionSummary permissionSummary;
    private final Corpus corpus;
    private final Subset masterSubset;
    private final Map<Object, SubsetItem> subsetItemMap;
    private final String corpusTitle;
    private Lang thesaurusLang;
    private final short masterCategory;

    public SatelliteFicheCreationHtmlProducer(BdfParameters bdfParameters, Corpus corpus) {
        super(bdfParameters);
        this.permissionSummary = bdfParameters.getPermissionSummary();
        this.corpus = corpus;
        masterSubset = corpus.getMasterSubset();
        if (masterSubset instanceof Corpus) {
            subsetItemMap = new TreeMap<Object, SubsetItem>();
        } else if (masterSubset instanceof Thesaurus) {
            subsetItemMap = new LinkedHashMap<Object, SubsetItem>();
            thesaurusLang = BdfServerUtils.checkLangDisponibility(bdfServer, (Thesaurus) masterSubset, workingLang);
        } else {
            throw new UnsupportedOperationException("Unable to deal with masterSubsetCategory: " + masterSubset.getSubsetKeyString());
        }
        masterCategory = masterSubset.getSubsetKey().getCategory();
        initSubsetItemMap();
        corpusTitle = FichothequeUtils.getTitle(corpus, workingLang);
    }

    @Override
    public void printHtml() {
        String masterSubsetTitle = FichothequeUtils.getTitle(masterSubset, workingLang);
        start();
        if (subsetItemMap.isEmpty()) {
            setCommandMessage(LogUtils.error(EditionHtmlUtils.getSatelliteAllErrMessageKey(masterCategory), corpusTitle, masterSubsetTitle));
            printCommandMessageUnit();
        } else {
            HtmlAttributes select = name(InteractionConstants.ID_PARAMNAME);
            this
                    .__(PageUnit.start("action-FicheCreate", new Litteral(CorpusMetadataUtils.getNewFicheLabel(corpus, workingLang))))
                    .P()
                    .__localize(EditionHtmlUtils.getSatelliteInfoMessageKey(masterCategory), corpusTitle, masterSubsetTitle)
                    ._P()
                    .FORM_get(Domains.EDITION)
                    .INPUT_hidden(ParameterMap.init()
                            .subset(corpus)
                            .page(EditionDomain.FICHE_CHANGE_PAGE)
                            .param(EditionDomain.FORCE_PARAMNAME, "1"))
                    .P()
                    .LABEL_for(select.id())
                    .__localize(EditionHtmlUtils.getMasterSelectMessageKey(masterCategory))
                    ._LABEL()
                    .__colon()
                    ._P()
                    .DIV("grid-InputCell")
                    .SELECT(select)
                    .__(printOptions())
                    ._SELECT()
                    ._DIV()
                    .__(Button.COMMAND, NEW_BUTTON)
                    ._FORM()
                    .__(PageUnit.END);
        }
        end();
    }

    private boolean printOptions() {
        for (SubsetItem subsetItem : subsetItemMap.values()) {
            if (subsetItem instanceof FicheMeta) {
                printOption((FicheMeta) subsetItem);
            } else if (subsetItem instanceof Motcle) {
                printOption((Motcle) subsetItem);
            }
        }
        return true;
    }

    private boolean printOption(FicheMeta ficheMeta) {
        String ficheTitle = CorpusMetadataUtils.getFicheTitle(ficheMeta, workingLang, bdfUser.getFormatLocale());
        this
                .OPTION(String.valueOf(ficheMeta.getId()), false)
                .__escape(ficheTitle)
                ._OPTION();
        return true;
    }

    private boolean printOption(Motcle motcle) {
        this
                .OPTION(String.valueOf(motcle.getId()), false);
        for (int i = 1; i < motcle.getLevel(); i++) {
            this
                    .__doublespace();
        }
        this
                .__(BdfHtmlUtils.printMotcleTitle(this, motcle, thesaurusLang))
                ._OPTION();
        return true;
    }

    private void initSubsetItemMap() {
        if (!permissionSummary.canCreate(corpus)) {
            return;
        }
        if (masterSubset instanceof Corpus) {
            for (SubsetItem subsetItem : masterSubset.getSubsetItemList()) {
                int id = subsetItem.getId();
                if (corpus.getFicheMetaById(id) == null) {
                    subsetItemMap.put(id, subsetItem);
                }
            }
        } else {
            List<Motcle> motcleList = ThesaurusUtils.toHierarchicMotcleList((Thesaurus) masterSubset);
            for (Motcle motcle : motcleList) {
                int id = motcle.getId();
                if (corpus.getFicheMetaById(id) == null) {
                    subsetItemMap.put(id, motcle);
                }
            }
        }

    }


}
