/* BdfServer_Commands - Copyright (c) 2021-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.commands.configuration;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.storage.IconScanEngine;
import fr.exemole.bdfserver.tools.storage.StorageUtils;
import java.io.IOException;
import java.io.InputStream;
import net.fichotheque.EditOrigin;
import net.mapeadores.util.exceptions.NestedIOException;
import net.mapeadores.util.io.ResourceUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.FileValue;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.RelativePath;


/**
 *
 * @author Vincent Calame
 */
public class CustomIconUploadCommand extends AbstractBdfCommand {

    public final static String COMMANDNAME = "LogoUpload";
    public final static String COMMANDKEY = "_ CNF-09";
    public final static String FILE_PARAMNAME = "file";
    public final static String REL_PARAMNAME = "rel";
    public final static String SIZES_PARAMNAME = "sizes";
    public final static String ICON_REL_PARAMVALUE = "icon";
    public final static String TOUCH_REL_PARAMVALUE = "touch";
    public final static String SHORTCUT_REL_PARAMVALUE = "shortcut";
    private String basename;

    public CustomIconUploadCommand(BdfServer bdfServer, RequestMap requestMap) {
        super(bdfServer, requestMap);
    }

    @Override
    public boolean needSynchronisation() {
        return true;
    }

    @Override
    protected void doCommand() throws ErrorMessageException {
        FileValue fileValue = requestHandler.getRequestMap().getFileValue(FILE_PARAMNAME);
        if (fileValue == null) {
            throw BdfErrors.emptyMandatoryParameter(FILE_PARAMNAME);
        }
        if (fileValue.length() < 2) {
            fileValue.free();
            throw BdfErrors.error("_ error.empty.file");
        }
        String resourceName = checkExtension(fileValue.getName());
        if (resourceName == null) {
            fileValue.free();
            throw BdfErrors.error("_ error.empty.extension", fileValue.getName());
        }
        RelativePath relativePath = IconScanEngine.ICON_FOLDER.buildChild(resourceName);
        EditOrigin editOrigin = bdfUser.newEditOrigin(Domains.CONFIGURATION, COMMANDNAME);
        try (InputStream is = fileValue.getInputStream()) {
            StorageUtils.saveResource(bdfServer, relativePath, is, editOrigin);
        } catch (IOException ioe) {
            throw new NestedIOException(ioe);
        } finally {
            fileValue.free();
        }
        putResultObject(RELATIVEPATH_OBJ, relativePath);
        setDone("_ done.configuration.customiconupload");
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        String prefix = getPrefix(getMandatory(REL_PARAMNAME));
        String sizes = getMandatory(SIZES_PARAMNAME).trim();
        sizes = sizes.replace(" ", "_");
        String name = prefix + sizes;
        if (!ResourceUtils.isValidResourceName(name + ".png")) {
            throw BdfErrors.error("_ error.wrong.sizes", sizes);
        }
        this.basename = name;
    }

    private String checkExtension(String fileName) {
        int idx = fileName.lastIndexOf(".");
        if (idx == -1) {
            return null;
        }
        String extension = fileName.substring(idx + 1).toLowerCase();
        if (extension.isEmpty()) {
            return null;
        }
        String result = basename + "." + extension;
        if (!ResourceUtils.isValidResourceName(result)) {
            return null;
        }
        return result;
    }

    private static String getPrefix(String rel) throws ErrorMessageException {
        switch (rel) {
            case ICON_REL_PARAMVALUE:
                return IconScanEngine.ICON_PREFIX;
            case TOUCH_REL_PARAMVALUE:
                return IconScanEngine.APPLETOUCHICON_PREFIX;
            case SHORTCUT_REL_PARAMVALUE:
                return IconScanEngine.SHORTCUTICON_PREFIX;
            default:
                throw BdfErrors.unknownParameterValue(REL_PARAMNAME, rel);

        }
    }


}
