/* BdfServer_Commands - Copyright (c) 2011-2026 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.album;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.IIOException;
import net.fichotheque.album.Album;
import net.fichotheque.utils.AlbumUtils;
import net.mapeadores.util.images.ImagesUtils;
import net.mapeadores.util.io.IOUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.FileValue;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "IllustrationFileUpload";
    public final static String COMMANDKEY = "_ ALB-07";
    public final static String FILE_PARAMNAME = "file";
    private Album album;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        FileValue fileValue = requestHandler.getRequestMap().getFileValue(FILE_PARAMNAME);
        if (fileValue == null) {
            throw BdfErrors.emptyMandatoryParameter(FILE_PARAMNAME);
        }
        File tmpFile = saveFile(fileValue);
        setDone("_ done.album.illustrationfileupload");
        putResultObject(TMPFILE_OBJ, tmpFile);
        putResultObject(ALBUM_OBJ, album);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        album = requestHandler.getMandatoryAlbum();
    }

    private File saveFile(FileValue fileValue) throws ErrorMessageException {
        long length = fileValue.length();
        if (length < 2) {
            fileValue.free();
            throw BdfErrors.error("_ error.empty.file");
        }
        String extension = AlbumUtils.checkExtension(fileValue.getName());
        if (extension == null) {
            fileValue.free();
            throw BdfErrors.error("_ error.wrong.imageextension");
        }
        try (InputStream is = fileValue.getInputStream()) {
            return saveFile(bdfServer, is, extension, album);
        } catch (IOException ioe) {
            throw BdfErrors.ioException(ioe);
        } finally {
            fileValue.free();
        }
    }

    public static File saveFile(BdfServer bdfServer, InputStream inputStream, String extension, Album album) throws IOException, ErrorMessageException {
        File tmpFile;
        String conversionExtension = AlbumUtils.getConversionExtension(extension);
        if (conversionExtension != null) {
            tmpFile = AlbumCommandUtils.getTmpFile(bdfServer, conversionExtension);
            BufferedImage srcImg = ImagesUtils.read(inputStream);
            ImagesUtils.write(srcImg, conversionExtension, tmpFile);
        } else {
            byte[] array = IOUtils.toByteArray(inputStream);
            try {
                BufferedImage srcImg = ImagesUtils.read(new ByteArrayInputStream(array));
            } catch (IOException ioe) {
                if (ioe instanceof IIOException) {
                    throw new ErrorMessageException("_ error.unsupported.imagetype");
                } else {
                    throw new ErrorMessageException("_ error.exception.io", ioe.getMessage());
                }
            }
            tmpFile = AlbumCommandUtils.getTmpFile(bdfServer, extension);
            try (OutputStream os = new FileOutputStream(tmpFile)) {
                IOUtils.copy(new ByteArrayInputStream(array), os);
            }
        }
        AlbumCommandUtils.minimizeTmpFile(tmpFile, album);
        return tmpFile;
    }

}
