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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.diagnostic.urlscan.UrlInfo;
import fr.exemole.bdfserver.tools.diagnostic.urlscan.UrlReport;
import fr.exemole.bdfserver.tools.diagnostic.urlscan.UrlReportCache;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.util.ArrayList;
import java.util.List;
import net.mapeadores.util.http.UrlStatus;
import net.mapeadores.util.http.UrlTestEngine;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "UrlTest";
    public final static String URL_PARAMNAME = "url";
    private String[] urlArray;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        List<UrlReport> urlReportList = new ArrayList<UrlReport>();
        List<UrlInfo> urlInfoList = new ArrayList<UrlInfo>();
        for (String url : urlArray) {
            UrlStatus urlStatus = UrlTestEngine.test(url);
            UrlReport urlReport = new UrlReport(url, urlStatus, System.currentTimeMillis());
            urlReportList.add(urlReport);
            urlInfoList.add(UrlInfo.init(url, urlReport));
        }
        UrlReportCache cache = new UrlReportCache(bdfServer);
        cache.cache(urlReportList, true);
        putResultObject(URLINFOCOLLECTION_OBJ, urlInfoList);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        urlArray = requestHandler.getTokens(URL_PARAMNAME);
        if (urlArray.length == 0) {
            throw BdfErrors.emptyMandatoryParameter(URL_PARAMNAME);
        }
    }

}
