/* BdfServer_HtmlProducers - Copyright (c) 2015-2024 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.addenda;

import fr.exemole.bdfserver.api.instruction.BdfParameters;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.interaction.domains.AddendaDomain;
import fr.exemole.bdfserver.html.BdfHtmlConstants;
import fr.exemole.bdfserver.html.BdfHtmlUtils;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.html.consumers.Button;
import fr.exemole.bdfserver.html.consumers.PageUnit;
import fr.exemole.bdfserver.html.consumers.Tree;
import fr.exemole.bdfserver.html.consumers.attributes.Deploy;
import fr.exemole.bdfserver.html.jslib.BdfJsLibs;
import fr.exemole.bdfserver.tools.BH;
import java.text.MessageFormat;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import net.fichotheque.SubsetItem;
import net.fichotheque.addenda.Addenda;
import net.fichotheque.addenda.Document;
import net.fichotheque.addenda.Version;
import net.fichotheque.permission.PermissionEntry;
import net.fichotheque.permission.PermissionSummary;
import net.fichotheque.tools.permission.ListFilterEngine;
import net.fichotheque.utils.FichothequeUtils;
import net.mapeadores.util.html.HA;
import net.mapeadores.util.html.HtmlConstants;
import net.mapeadores.util.html.HtmlWrapper;


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

    private final static HtmlWrapper VERSION_TREE = Tree.tree("addenda-VersionTree");
    private final static HtmlWrapper VERSION_LEAF = Tree.tree("addenda-VersionLeaf");
    private final PermissionSummary permissionSummary;
    private final Addenda addenda;
    private final boolean isSubsetAdmin;
    private final MessageFormat idFormat;
    private final Button linkButton = Button.link();

    public AddendaHtmlProducer(BdfParameters bdfParameters, Addenda addenda) {
        super(bdfParameters);
        this.permissionSummary = bdfParameters.getPermissionSummary();
        this.addenda = addenda;
        this.isSubsetAdmin = permissionSummary.isSubsetAdmin(addenda.getSubsetKey());
        this.idFormat = new MessageFormat(getLocalization("_ info.main.documentnumber"), getFormatLocale());
        addJsLib(BdfJsLibs.SUBSETCHANGE);
        addThemeCss("addenda.css");
        setBodyCssClass("global-body-ListFrame");
    }

    @Override
    public void printHtml() {
        List<PermissionEntry> permissionEntryList;
        int count;
        List<SubsetItem> documentList = addenda.getSubsetItemList();
        if (!documentList.isEmpty()) {
            permissionEntryList = ListFilterEngine.filter(addenda, documentList, permissionSummary);
            count = permissionEntryList.size();
        } else {
            permissionEntryList = null;
            count = 0;
        }
        start(FichothequeUtils.getTitle(addenda, workingLang), true);
        this
                .__(BdfHtmlUtils.startSubsetUnit(this, bdfParameters, addenda, AddendaDomain.ADDENDA_PAGE))
                .__(printCommands())
                .__(PageUnit.END);
        if (count > 0) {
            this
                    .__(PageUnit.start().sectionCss("unit-Unit addenda-DocumentListUnit").title(() -> {
                        this
                                .__localize("_ title.addenda.documents")
                                .__space()
                                .__(BdfHtmlUtils.printItemCount(this, bdfUser, count));
                    }))
                    .UL("subsetitem-List")
                    .__(printDocumentList(permissionEntryList))
                    ._UL()
                    .__(PageUnit.END);
        }
        end();
    }

    private boolean printCommands() {
        if (!isSubsetAdmin) {
            return false;
        }
        this
                .DETAILS(HA.id("details_commands").open(true).classes("tools-Details").populate(Deploy.DETAILS))
                .SUMMARY()
                .__localize("_ title.global.commands")
                ._SUMMARY()
                .DIV("tools-List")
                .__(link("action-Metadata", AddendaDomain.ADDENDA_METADATAFORM_PAGE, "_ link.addenda.addendametadataform"))
                .__(link("action-Advanced", AddendaDomain.ADDENDA_ADVANCEDCOMMANDS_PAGE, "_ link.addenda.addendaadvancedcommands"))
                .__(link("action-Refresh", AddendaDomain.ADDENDA_PAGE, "_ link.global.reload"))
                ._DIV()
                ._DETAILS();
        return true;
    }

    private Button link(String action, String page, String messageKey) {
        String href = BH.domain(Domains.ADDENDA).subset(addenda).page(page).toString();
        String target;
        if (page.equals(AddendaDomain.ADDENDA_PAGE)) {
            target = null;
        } else {
            target = BdfHtmlConstants.EDITION_FRAME;
        }
        return linkButton.href(href).action(action).textL10nObject(messageKey).target(target);
    }

    private boolean printDocumentList(List<PermissionEntry> entryList) {
        SortedMap<String, PermissionEntry> sortMap = new TreeMap<String, PermissionEntry>();
        for (PermissionEntry entry : entryList) {
            sortMap.put(((Document) entry.getSubsetItem()).getBasename(), entry);
        }
        for (PermissionEntry permissionEntry : sortMap.values()) {
            this
                    .LI()
                    .__(printDocument((Document) permissionEntry.getSubsetItem(), permissionEntry.isEditable()))
                    ._LI();
        }
        return true;
    }

    private boolean printDocument(Document document, boolean editable) {
        String basename = document.getBasename();
        Object[] objs = new Object[1];
        objs[0] = document.getId();
        this
                .DIV("subsetitem-Title")
                .P()
                .__escape(basename)
                ._P()
                .__(printDocumentEdit(editable, document))
                ._DIV()
                .DIV("subsetitem-Infos")
                .__escape(idFormat.format(objs))
                ._DIV()
                .__(VERSION_TREE, () -> {
                    for (Version version : document.getVersionList()) {
                        String extension = version.getExtension();
                        this
                                .__(VERSION_LEAF, () -> {
                                    this
                                            .A(HA.href("documents/" + addenda.getSubsetName() + "/" + basename + "." + extension).target(HtmlConstants.BLANK_TARGET))
                                            .__escape('.')
                                            .__escape(extension)
                                            ._A()
                                            .SPAN("addenda-Size")
                                            .__space()
                                            .__escape('(')
                                            .__(BdfHtmlUtils.printDocumentVersionSize(this, version, getFormatLocale()))
                                            .__escape(')')
                                            ._SPAN();
                                });
                    }
                });
        return true;
    }

    private boolean printDocumentEdit(boolean editable, Document document) {
        if (!editable) {
            return false;
        }
        this
                .A(HA.href(BH.domain(Domains.ADDENDA).subsetItem(document).page(AddendaDomain.DOCUMENT_ADMINFORM_PAGE)).target(BdfHtmlConstants.EDITION_FRAME).classes("button-Circle action-DocumentEdit"))
                .__(Button.ICON)
                ._A();
        return true;
    }

}
