/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2022 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jboss.installer.validators;

import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.ValidationResult;

import java.nio.file.Files;
import java.nio.file.Path;

public class FileValidator {

    public static final String IS_DIRECTORY_ERROR = "security_domain_screen.is_directory_error";
    public static final String NOT_ABSOLUTE_ERROR = "security_domain_screen.not_absolute_error";
    public static final String NOT_EXISTS_ERROR = "security_domain_screen.not_exists_error";
    private final LanguageUtils langUtils;
    private final boolean notExistAllowed;

    public FileValidator(LanguageUtils langUtils) {
        this.langUtils = langUtils;
        this.notExistAllowed = false;
    }

    public FileValidator(LanguageUtils langUtils, boolean notExistAllowed) {
        this.langUtils = langUtils;
        this.notExistAllowed = notExistAllowed;
    }

    public ValidationResult validate(Path path) {
        if (!path.isAbsolute()) {
            return ValidationResult.error(langUtils.getString(NOT_ABSOLUTE_ERROR, path.toString()));
        }
        if (!notExistAllowed && Files.notExists(path)) {
            return ValidationResult.error(langUtils.getString(NOT_EXISTS_ERROR, path.toString()));
        }
        if (Files.isDirectory(path)) {
            return ValidationResult.error(langUtils.getString(IS_DIRECTORY_ERROR, path.toString()));
        }
        return ValidationResult.ok();
    }
}
