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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.fichotheque.album.Album;
import net.fichotheque.utils.AlbumUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.mimetype.MimeTypeConstants;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "IllustrationFileDownload";
    public final static String COMMANDKEY = "_ ALB-08";
    public final static String URL_PARAMNAME = "url";
    private Album album;
    private String extension;
    private HttpURLConnection httpURLConnection;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        File tmpFile = null;
        try (InputStream is = httpURLConnection.getInputStream()) {
            tmpFile = IllustrationFileUploadCommand.saveFile(bdfServer, is, extension, album);
        } catch (IOException ioe) {
            throw BdfErrors.ioException(ioe);
        }
        if (tmpFile != null) {
            setDone("_ done.album.illustrationfiledownload");
            putResultObject(TMPFILE_OBJ, tmpFile);
            putResultObject(ALBUM_OBJ, album);
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        album = requestHandler.getMandatoryAlbum();
        String urlString = getMandatory(URL_PARAMNAME);
        URL imageURL;
        try {
            imageURL = new URL(urlString);
        } catch (MalformedURLException mue) {
            throw BdfErrors.error("_ error.wrong.url", urlString);
        }
        String protocol = imageURL.getProtocol();
        if ((protocol == null) || (protocol.isEmpty())) {
            throw BdfErrors.error("_ error.wrong.url", urlString);
        }
        switch (protocol) {
            case "http":
            case "https":
                break;
            default:
                throw BdfErrors.error("_ error.unknown.url_protocol", protocol);

        }
        try {
            HttpURLConnection urlConnection = (HttpURLConnection) imageURL.openConnection();
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.connect();
            int code = urlConnection.getResponseCode();
            if (code != 200) {
                throw BdfErrors.error("_ error.exception.url_httpcode", code);
            }
            String format;
            String mimetype = urlConnection.getContentType();
            if ((mimetype != null) && (!mimetype.equals(MimeTypeConstants.OCTETSTREAM))) {
                int idx = mimetype.indexOf("/");
                format = AlbumUtils.checkExtension("img." + mimetype.substring(idx + 1));
                if (format == null) {
                    throw BdfErrors.error("_ error.unknown.url_mimetype", mimetype);
                }
            } else {
                int idx = urlString.lastIndexOf("/");
                format = AlbumUtils.checkExtension(urlString.substring(idx + 1));
                if (format == null) {
                    throw BdfErrors.error("_ error.wrong.url_imageextension", mimetype);
                }
            }
            this.httpURLConnection = urlConnection;
            this.extension = format;
        } catch (IOException ioe) {
            throw BdfErrors.error("_ error.exception.url_io", imageURL);
        }
    }

}
