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

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.ConfigurationDomain;
import fr.exemole.bdfserver.commands.administration.ResourceUploadCommand;
import fr.exemole.bdfserver.commands.configuration.OdtLogoChangeCommand;
import fr.exemole.bdfserver.html.BdfServerHtmlProducer;
import fr.exemole.bdfserver.html.consumers.Grid;
import fr.exemole.bdfserver.html.consumers.PageUnit;
import fr.exemole.bdfserver.html.jslib.BdfJsLibs;
import fr.exemole.bdfserver.tools.configuration.ConfigurationUtils;
import fr.exemole.bdfserver.tools.instruction.BdfInstructionUtils;
import fr.exemole.bdfserver.tools.storage.IconScanEngine;
import fr.exemole.bdfserver.tools.storage.StorageUtils;
import java.util.List;
import java.util.Map;
import net.mapeadores.util.exceptions.SwitchException;
import net.mapeadores.util.html.CommandBox;
import net.mapeadores.util.html.HA;
import net.mapeadores.util.html.HtmlAttributes;
import net.mapeadores.util.localisation.Litteral;
import net.mapeadores.util.text.RelativePath;


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

    public LogosFormHtmlProducer(BdfParameters bdfParameters) {
        super(bdfParameters);
        addJsLib(BdfJsLibs.COMMANDVEIL);
        addThemeCss("configuration.css");
    }

    @Override
    public void printHtml() {
        start();
        printCommandMessageUnit();
        CommandBox commandBox = CommandBox.init()
                .action(Domains.CONFIGURATION)
                .family("CNF")
                .veil(true)
                .page(ConfigurationDomain.LOGOSFORM_PAGE)
                .name(BdfInstructionUtils.getAbsoluteCommandName(Domains.ADMINISTRATION, ResourceUploadCommand.COMMANDNAME))
                .multipart(true)
                .actionCssClass("action-Save")
                .submitLocKey("_ submit.administration.resourceupload");
        printLogoBox(commandBox);
        printIconBox(commandBox, "16");
        printIconBox(commandBox, "32");
        printOdtLogoBox();
        printExistingCustomIconUnit();
        ConfigurationCommandBoxUtils.printCustomIconUploadBox(this, commandBox);
        end();
    }


    private void printIconBox(CommandBox commandBox, String size) {
        RelativePath relativePath = getRelativePath(size);
        boolean containsIcon = StorageUtils.containsVarResource(bdfServer, relativePath);
        commandBox
                .lockey(getCommandLockKey(size))
                .hidden(InteractionConstants.PATH_PARAMNAME, relativePath.toString());
        this
                .__start(commandBox)
                .__(Grid.START)
                .__(printImageRow(containsIcon, HA.src(relativePath.toString()).alt("icon " + size + "x" + size).classes("configuration-Logo").height(size).width(size)))
                .__(printFileInput("_ label.configuration.file_icon"))
                .__(Grid.END)
                .__end(commandBox);
    }

    private boolean printLogoBox(CommandBox commandBox) {
        boolean containsLogo = bdfServer.getResourceStorages().containsResource(StorageUtils.LOGO);
        commandBox
                .lockey(ResourceUploadCommand.LOGO_COMMANDKEY)
                .hidden(InteractionConstants.PATH_PARAMNAME, StorageUtils.LOGO.toString());
        this
                .__start(commandBox)
                .__(Grid.START)
                .__(printLogoRow(containsLogo, HA.src("images/logo.png").alt("logo").classes("configuration-Logo")))
                .__(printFileInput("_ label.configuration.file_logo"))
                .__(Grid.END)
                .__end(commandBox);
        return true;
    }

    private boolean printImageRow(boolean contains, HtmlAttributes imgAttributes) {
        String locKey = (contains) ? "_ label.configuration.icon_current" : "_ label.configuration.icon_default";
        this
                .__(Grid.START_ROW)
                .__(Grid.labelCells(locKey))
                .__(Grid.START_INPUTCELL)
                .IMG(imgAttributes)
                .__(Grid.END_INPUTCELL)
                .__(Grid.END_ROW);
        return true;
    }

    private boolean printLogoRow(boolean contains, HtmlAttributes imgAttributes) {
        if (contains) {
            this
                    .__(Grid.START_ROW)
                    .__(Grid.labelCells("_ label.configuration.logo_current"))
                    .__(Grid.START_INPUTCELL)
                    .IMG(imgAttributes)
                    .__(Grid.END_INPUTCELL)
                    .__(Grid.END_ROW);
        } else {
            this
                    .__(Grid.START_ROW)
                    .__(Grid.START_UNIQUECELL)
                    .__localize("_ info.configuration.nologo")
                    .__(Grid.END_UNIQUECELL)
                    .__(Grid.END_ROW);
        }
        return true;
    }

    private boolean printFileInput(String messageKey) {
        this
                .__(Grid.fileInputRow(messageKey, name(ResourceUploadCommand.FILE_PARAMNAME).size("75").classes("global-FileInput")));
        return true;
    }

    private boolean printExistingCustomIconUnit() {
        List<HtmlAttributes> existingList = IconScanEngine.run(bdfServer.getResourceStorages(), bdfServer.getMimeTypeResolver());
        this
                .__(PageUnit.start("action-Logos", "_ title.configuration.customincons"));
        if (existingList.isEmpty()) {
            this
                    .P()
                    .__localize("_ info.configuration.empty_customincons")
                    .P();
        } else {
            this
                    .__(Grid.START);
            for (HtmlAttributes htmlAttributes : existingList) {
                HtmlAttributes imgAttributes = HA.src(htmlAttributes.href()).classes("configuration-Logo");
                String labelText;
                String sizes = htmlAttributes.attr("sizes");
                if (sizes != null) {
                    labelText = sizes + " (" + htmlAttributes.rel() + ")";
                } else {
                    labelText = htmlAttributes.rel();
                }
                this
                        .__(Grid.START_ROW)
                        .__(Grid.labelCells(new Litteral(labelText)))
                        .__(Grid.START_INPUTCELL)
                        .IMG(imgAttributes)
                        .__(Grid.END_INPUTCELL)
                        .__(Grid.END_ROW);
            }
            this
                    .__(Grid.END);

        }
        this
                .__(PageUnit.END);
        return true;
    }

    private void printOdtLogoBox() {
        Map<String, String> logoMap = ConfigurationUtils.getOdtLogoParameters(bdfServer);
        CommandBox commandBox = CommandBox.init()
                .action(Domains.CONFIGURATION)
                .lockey(OdtLogoChangeCommand.COMMANDKEY)
                .family("CNF")
                .veil(true)
                .page(ConfigurationDomain.LOGOSFORM_PAGE)
                .name(OdtLogoChangeCommand.COMMANDNAME)
                .multipart(true)
                .actionCssClass("action-Odt")
                .submitLocKey("_ submit.configuration.odtlogochange");
        String path = logoMap.get("path");
        boolean withCurrent = false;
        HtmlAttributes logoImg = null;
        if (path != null) {
            withCurrent = true;
            logoImg = HA.src(path).alt("logo").classes("configuration-Logo");
        }
        this
                .__start(commandBox)
                .__(Grid.START)
                .__(printLogoRow(withCurrent, logoImg))
                .__(Grid.fileInputRow("_ label.configuration.file_logo_odt", name(OdtLogoChangeCommand.FILE_PARAMNAME).size("75").classes("global-FileInput")))
                .__(Grid.textInputRow("_ label.configuration.odtlogowidth", name(OdtLogoChangeCommand.WIDTH_PARAMNAME).size("30").value(logoMap.get("width"))))
                .__(Grid.textInputRow("_ label.configuration.odtlogoheight", name(OdtLogoChangeCommand.HEIGHT_PARAMNAME).size("30").value(logoMap.get("height"))))
                .__(Grid.END)
                .__end(commandBox);
    }


    private static String getCommandLockKey(String size) {
        switch (size) {
            case "16":
                return ResourceUploadCommand.ICON16_COMMANDKEY;
            case "32":
                return ResourceUploadCommand.ICON32_COMMANDKEY;
            default:
                throw new SwitchException("Unknown size: " + size);
        }
    }

    private static RelativePath getRelativePath(String size) {
        switch (size) {
            case "16":
                return StorageUtils.ICON;
            case "32":
                return StorageUtils.ICON32;
            default:
                throw new SwitchException("Unknown size: " + size);
        }
    }

}
