/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2021 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.io.File;
import java.nio.file.Files;
import java.nio.file.Path;


public class WritableFolderValidator {

    public static final String NOT_WRITEABLE_KEY="notwritable";
    public static final String NON_EMPTY_KEY="nonempty";
    public static final String IS_FILE="isfile";
    public static final String NOT_ABSOLUTE_PATH="notabsolute";
    public static final boolean EMPTY_DIRECTORY_ENABLED = true;
    public static final boolean EMPTY_DIRECTORY_DISABLED = false;

    private final PathValidator pathValidator;

    public WritableFolderValidator(String prefix, LanguageUtils langUtils) {
        this.pathValidator = PathValidator.newInstance(prefix, langUtils);
    }

    public ValidationResult validate(String installPathText, boolean emptyDirectoryAllowed) {
        if (installPathText == null) {
            return ValidationResult.error(pathValidator.getErrorMessage(PathValidator.NO_PATH_KEY));
        }

        ValidationResult pathValidationResult = pathValidator.validate(installPathText);
        if (pathValidationResult.getResult() == ValidationResult.Result.ERROR) {
            return pathValidationResult;
        }

        final Path path = Path.of(installPathText);
        if (pathValidationResult.getResult() == ValidationResult.Result.OK) {
            return validate(path, emptyDirectoryAllowed);
        } else {
            // check the full validation, if no other errors, return the warning
            ValidationResult fullResults = validate(path, emptyDirectoryAllowed);
            if (fullResults.getResult() == ValidationResult.Result.OK) {
                return pathValidationResult;
            } else {
                return fullResults;
            }
        }
    }

    public ValidationResult validate(Path installPath, boolean emptyDirectoryAllowed) {
        if (installPath == null) {
            return ValidationResult.error(pathValidator.getErrorMessage(PathValidator.NO_PATH_KEY));
        }

        if (!installPath.isAbsolute()) {
            return ValidationResult.error(pathValidator.getErrorMessage(NOT_ABSOLUTE_PATH));
        }
        File parentDirectory = installPath.getParent().toFile();
        if (Files.isRegularFile(installPath)) {
            return ValidationResult.error(pathValidator.getErrorMessage(IS_FILE));
        }

        if (Files.isDirectory(installPath)) {
            if (!emptyDirectoryAllowed && !isEmpty(installPath)) {
                return ValidationResult.error(pathValidator.getErrorMessage(NON_EMPTY_KEY));
            }
            if (!installPath.toFile().canWrite()) {
                return ValidationResult.error(pathValidator.getErrorMessage(NOT_WRITEABLE_KEY));
            }
        } else {
            parentDirectory = getExistingParent(parentDirectory);
            if (parentDirectory == null || !parentDirectory.canWrite()) {
                return ValidationResult.error(pathValidator.getErrorMessage(NOT_WRITEABLE_KEY));
            }
        }

        return ValidationResult.ok();
    }

    public File getExistingParent(File dir) {
        while (dir != null && !dir.exists()) {
            dir = dir.getParentFile();
        }
        return dir;
    }

    public boolean isEmpty(Path path) {
        return path.toFile().listFiles().length == 0;
    }
}
