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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import java.io.IOException;
import net.mapeadores.util.exceptions.ResponseCodeException;
import net.mapeadores.util.exceptions.ResponseContentTypeException;
import net.mapeadores.util.html.MetaReport;
import net.mapeadores.util.html.jsoup.MetaReportEngine;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "MetaReport";
    public final static String URL_PARAMNAME = "url";
    private String url;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        try {
            MetaReport metaReport = MetaReportEngine.run(url);
            putResultObject(METAREPORT_OBJ, metaReport);
        } catch (IOException ioe) {
            throw new ErrorMessageException("_ error.exception.url_io", ioe.getMessage());
        } catch (IllegalArgumentException iae) {
            throw new ErrorMessageException("_ label.diagnostic.error_malformedurl");
        } catch (ResponseCodeException rce) {
            throw new ErrorMessageException("_ error.exception.url_httpcode", rce.getHttpStatusCode());
        } catch (ResponseContentTypeException rcte) {
            String contentType = rcte.getContentType();
            if (contentType == null) {
                throw new ErrorMessageException("_ error.exception.url_contentType_unknown");
            } else {
                throw new ErrorMessageException("_ error.exception.url_contentType_unsupported", contentType);
            }
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        this.url = getMandatory(URL_PARAMNAME);
    }

}
