/* BdfServer_Commands - Copyright (c) 2012-2022 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.configuration.ConfigurationUtils;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.io.File;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "BackupDelete";
    public final static String COMMANDKEY = "_ ADM-02";
    public final static String BACKUP_PARAMNAME = "backup";
    private File backupFile;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        boolean done = backupFile.delete();
        if (done) {
            setDone("_ done.administration.backupdelete");
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        String backupName = getMandatory(BACKUP_PARAMNAME);
        if (!testName(backupName)) {
            throw BdfErrors.wrongParameterValue(BACKUP_PARAMNAME, backupName);
        }
        File backupDirectory = ConfigurationUtils.getBackupDirectory(bdfServer);
        backupFile = new File(backupDirectory, backupName);
    }

    private static boolean testName(String name) {
        int length = name.length();
        for (int i = 0; i < length; i++) {
            char carac = name.charAt(i);
            boolean ok = false;
            switch (carac) {
                case '.':
                case '-':
                case '_':
                    ok = true;
            }
            if ((carac >= '0') && (carac <= '9')) {
                ok = true;
            } else if ((carac >= 'a') && (carac <= 'z')) {
                ok = true;
            }
            if (!ok) {
                return false;
            }
        }
        return true;
    }

}
