/* BdfServer_HtmlProducers - Copyright (c) 2012-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.administration;

import fr.exemole.bdfserver.api.instruction.BdfParameters;
import fr.exemole.bdfserver.api.interaction.Domain;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.interaction.GetConstants;
import fr.exemole.bdfserver.api.interaction.domains.AdministrationDomain;
import fr.exemole.bdfserver.api.interaction.domains.ConfigurationDomain;
import fr.exemole.bdfserver.api.interaction.domains.ExportationDomain;
import fr.exemole.bdfserver.api.interaction.domains.ImportationDomain;
import fr.exemole.bdfserver.api.interaction.domains.MiscDomain;
import fr.exemole.bdfserver.api.interaction.domains.SelectionDomain;
import fr.exemole.bdfserver.api.menu.ActionEntry;
import fr.exemole.bdfserver.api.menu.ActionGroup;
import fr.exemole.bdfserver.api.providers.ActionProvider;
import fr.exemole.bdfserver.commands.exportation.BalayageRunCommand;
import fr.exemole.bdfserver.html.BdfHtmlConstants;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.html.consumers.Button;
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 fr.exemole.bdfserver.tools.BdfServerUtils;
import java.util.List;
import net.fichotheque.exportation.balayage.BalayageDescription;
import net.fichotheque.permission.PermissionSummary;
import net.mapeadores.util.html.HA;
import net.mapeadores.util.html.HtmlConstants;
import net.mapeadores.util.localisation.Message;


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

    private final Button linkButton = Button.link();
    private final PermissionSummary permissionSummary;

    public IndexHtmlProducer(BdfParameters bdfParameters) {
        super(bdfParameters);
        this.permissionSummary = bdfParameters.getPermissionSummary();
        addJsLib(BdfJsLibs.DEPLOY);
        addThemeCss("administration.css");
        addThemeCssForAction(ActionProvider.ADMIN_KEY);
        setMainStorageKey(Domains.MAIN, AdministrationDomain.INDEX_PAGE);
    }

    @Override
    public void printHtml() {
        start();
        printCommandMessageUnit();
        this
                .__(printConfigurationGroup())
                .__(printRightsGroup())
                .__(printReportingGroup())
                .__(printCustomizationGroup())
                .__(printImportationGroup())
                .__(printExportationGroup())
                .__(printBalayageGroup())
                .__(printExtensionGroups());
        end();
    }


    private boolean printConfigurationGroup() {
        if (!permissionSummary.isFichothequeAdmin()) {
            return false;
        }
        boolean withExtensions = !bdfServer.getExtensionManager().getBdfExtensionReferenceList().isEmpty();
        this
                .__(startGroup("group_configuration", "_ title.administration.configurationlinks"))
                .__(link("action-Core", BH.domain(Domains.CONFIGURATION).page(ConfigurationDomain.COREFORM_PAGE), "_ link.configuration.core"))
                .__(link("action-Labels", BH.domain(Domains.CONFIGURATION).page(ConfigurationDomain.PHRASESFORM_PAGE), "_ link.configuration.phrasesform"))
                .__(link("action-Logos", BH.domain(Domains.CONFIGURATION).page(ConfigurationDomain.LOGOSFORM_PAGE), "_ link.configuration.logosform"))
                .__(link("action-Groups", BH.domain(Domains.CONFIGURATION).page(ConfigurationDomain.GROUPFORM_PAGE), "_ link.configuration.groupform"))
                .__(link("action-SubsetTrees", BH.domain(Domains.CONFIGURATION).page(ConfigurationDomain.SUBSETTREEFORM_PAGE), "_ link.configuration.subsettreeform"))
                .__if(withExtensions, IndexHtmlProducer.this.link("action-Extensions", BH.domain(Domains.CONFIGURATION).page(ConfigurationDomain.EXTENSIONSFORM_PAGE), "_ link.configuration.extensionsform"))
                .__(link("action-Advanced", BH.domain(Domains.CONFIGURATION).page(ConfigurationDomain.CONFIGADVANCEDCOMMANDS_PAGE), "_ link.configuration.advancedcommands"))
                .__(link("action-EtcConfig", BH.domain(Domains.CONFIGURATION).page(ConfigurationDomain.ETCCONFIG_PAGE), "_ link.configuration.etcconfig"))
                .__(endGroup());
        return true;
    }

    private boolean printRightsGroup() {
        if (!permissionSummary.isFichothequeAdmin()) {
            return false;
        }
        this
                .__(startGroup("group_rights", "_ title.administration.rightslinks"))
                .__(paneLink("action-Roles", Domains.ADMINISTRATION, AdministrationDomain.ROLES_PAGE, "_ link.administration.roleadmin"))
                .__(link("action-Ods", GetConstants.USERS_ROOT + "/_all.ods", "_ link.administration.rolesummary_all", BdfHtmlConstants.EDITION_FRAME))
                .__(endGroup());
        return true;
    }

    private boolean printReportingGroup() {
        if (!permissionSummary.isFichothequeAdmin()) {
            return false;
        }
        boolean withLog = !bdfServer.getInitLogs().isEmpty();
        this
                .__(startGroup("group_reporting", "_ title.administration.reportinglinks"))
                .__if((withLog), link("action-Logs", BH.domain(Domains.ADMINISTRATION).page(AdministrationDomain.INITLOG_PAGE), "_ title.administration.storageprocesslog"))
                .__(link("action-Stats", BH.domain(Domains.MISC).page(MiscDomain.GLOBALSTATS_PAGE), "_ title.misc.globalstats"))
                .__(link("action-Diagrams", BH.domain(Domains.MISC).page(MiscDomain.DIAGRAMS_PAGE), "_ title.misc.diagrams"))
                .__(link("action-Sessions", BH.domain(Domains.ADMINISTRATION).page(AdministrationDomain.SESSIONLIST_PAGE), "_ title.administration.sessionlist"))
                .__(link("action-Backup", BH.domain(Domains.ADMINISTRATION).page(AdministrationDomain.BACKUP_PAGE), "_ link.administration.backup"))
                .__(paneLink("action-Diagnostic", Domains.ADMINISTRATION, AdministrationDomain.DIAGNOSTIC_PAGE, "_ link.administration.diagnostic"))
                .__(endGroup());
        return true;
    }

    private boolean printCustomizationGroup() {
        if (!permissionSummary.isFichothequeAdmin()) {
            return false;
        }
        if (!isWithJavascript()) {
            return false;
        }
        this
                .__(startGroup("group_customization", "_ title.administration.customizationlinks"))
                .__(paneLink("action-Resources", Domains.ADMINISTRATION, AdministrationDomain.RESOURCES_PAGE, "_ link.administration.resourceadmin"))
                .__(paneLink("action-Transformations", Domains.EXPORTATION, ExportationDomain.TRANSFORMATIONS_PAGE, "_ link.exportation.transformationadmin"))
                .__(endGroup());
        return true;
    }

    private boolean printImportationGroup() {
        if (!permissionSummary.isFichothequeAdmin()) {
            return false;
        }
        this
                .__(startGroup("group_importation", "_ title.administration.importationlinks"))
                .__(link("action-Corpus", BH.domain(Domains.IMPORTATION).page(ImportationDomain.CORPUSIMPORT_PAGE), "_ title.importation.corpusimport"))
                .__(link("action-Thesaurus", BH.domain(Domains.IMPORTATION).page(ImportationDomain.THESAURUSIMPORT_PAGE), "_ title.importation.thesaurusimport"))
                .__(link("action-Labels", BH.domain(Domains.IMPORTATION).page(ImportationDomain.LABELIMPORT_PAGE), "_ title.importation.labelimport"))
                .__(endGroup());
        return true;
    }

    private boolean printExportationGroup() {
        if (!permissionSummary.isFichothequeAdmin()) {
            return false;
        }
        if (!isWithJavascript()) {
            return false;
        }
        this
                .__(startGroup("group_exportation", "_ title.administration.exportationlinks"))
                .__(paneLink("action-Selection", Domains.SELECTION, SelectionDomain.DEFS_PAGE, "_ link.selection.selectiondefadmin"))
                .__(paneLink("action-TableExports", Domains.EXPORTATION, ExportationDomain.TABLEEXPORTS_PAGE, "_ link.exportation.tableexportadmin"))
                .__(paneLink("action-Accesses", Domains.EXPORTATION, ExportationDomain.ACCESSES_PAGE, "_ link.exportation.accessadmin"))
                .__(paneLink("action-ScrutariExports", Domains.EXPORTATION, ExportationDomain.SCRUTARIEXPORTS_PAGE, "_ link.exportation.scrutariexportadmin"))
                .__(paneLink("action-SqlExports", Domains.EXPORTATION, ExportationDomain.SQLEXPORTS_PAGE, "_ link.exportation.sqlexportadmin"))
                .__(paneLink("action-Balayages", Domains.EXPORTATION, ExportationDomain.BALAYAGES_PAGE, "_ link.exportation.balayageadmin"))
                .__(endGroup());
        return true;
    }

    private boolean printBalayageGroup() {
        if (!permissionSummary.canDo("balayagerun")) {
            return false;
        }
        List<BalayageDescription> balayageDefList = bdfServer.getBalayageManager().getBalayageDescriptionList();
        if (balayageDefList.isEmpty()) {
            return false;
        }
        Button balayageLink = Button.link()
                .target(BdfHtmlConstants.EDITION_FRAME)
                .action("action-Run");
        this
                .__(startGroup("group_balayage", "_ title.exportation.balayageindex", "administration-Balayages"))
                .__(Tree.TREE, () -> {
                    for (BalayageDescription balayageDescription : balayageDefList) {
                        String balayageName = balayageDescription.getName();
                        this
                                .__(Tree.LEAF, () -> {
                                    this
                                            .__(balayageLink
                                                    .text(balayageName)
                                                    .tooltipMessage("_ link.exportation.balayagerun_long", balayageName)
                                                    .href(BH.domain(Domains.EXPORTATION).page(ExportationDomain.BALAYAGE_RESULT_PAGE).command(BalayageRunCommand.COMMANDNAME).pageErr(ExportationDomain.BALAYAGE_ERROR_PAGE).balayage(balayageName)));
                                });
                    }
                })
                .__(endGroup());
        return true;
    }

    private boolean printExtensionGroups() {
        if (!permissionSummary.isFichothequeAdmin()) {
            return false;
        }
        for (ActionGroup actionGroup : BdfServerUtils.getExtensionActionGroupList(ActionProvider.ADMIN_KEY, bdfServer, bdfUser)) {
            this
                    .DETAILS(HA.id("group_ext_" + actionGroup.getId()).classes("administration-Group").populate(Deploy.DETAILS))
                    .SUMMARY()
                    .__(printTitle(actionGroup.getTitle()))
                    ._SUMMARY()
                    .DIV("administration-List");
            for (ActionEntry actionEntry : actionGroup.getActionEntryList()) {
                String target = actionEntry.getTarget();
                if (target == null) {
                    target = BdfHtmlConstants.EDITION_FRAME;
                }
                this
                        .A(HA.href(actionEntry.getUrl()).target(target).classes("global-button-Link " + actionEntry.getCssName()))
                        .__(Button.ICON)
                        /*  */.SPAN("global-button-Text")
                        /*  */.__(printTitle(actionEntry.getTitle()))
                        /*  */._SPAN()
                        ._A();
            }
            this
                    .__(endGroup());
        }
        return true;
    }

    private Button link(String action, CharSequence href, String messageKey) {
        return link(action, href, messageKey, BdfHtmlConstants.EDITION_FRAME);
    }

    private Button link(String action, CharSequence href, String messageKey, String target) {
        return linkButton.href(href.toString()).action(action).textL10nObject(messageKey).target(target);
    }

    private Button paneLink(String action, String domain, String page, String messageKey) {
        if (!isWithJavascript()) {
            return null;
        }
        return linkButton.href(Domain.getCompleteDomain(domain, page)).action(action).textL10nObject(messageKey).target(HtmlConstants.BLANK_TARGET);
    }

    private boolean startGroup(String id, String summaryKey) {
        return startGroup(id, summaryKey, null);
    }

    private boolean startGroup(String id, String summaryKey, String supplementaryClasses) {
        String classes = "administration-Group";
        if (supplementaryClasses != null) {
            classes = classes + " " + supplementaryClasses;
        }
        this
                .DETAILS(HA.id(id).classes(classes).populate(Deploy.DETAILS))
                .SUMMARY()
                .__localize(summaryKey)
                ._SUMMARY()
                .DIV("administration-List");
        return true;
    }

    private boolean printTitle(Object titleObject) {
        if (titleObject instanceof Message) {
            this
                    .__localize((Message) titleObject);
        } else {
            this
                    .__escape(titleObject.toString());
        }
        return true;
    }

    private boolean endGroup() {
        this
                ._DIV()
                ._DETAILS();
        return true;
    }

}
