/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2023 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.Path;
import java.util.List;
import java.util.Set;

class LinuxPathValidator extends PathValidator {

    static final int LINUX_PATH_LENGTH_HARD_LIMIT = 4095; // One final char reserved for NUL
    static final Set<String> LINUX_INVALID_CHARACTERS = Set.of("\0", "//", ";", "\\", "\"", "?", "%", ":", "  ");
    private static final List<String> LINUX_INVALID_CHARACTERS_PRINT = List.of("'NUL'", "'//'", "';'", "'\\'", "'\"'", "'?'", "'%'", "':'");

    public LinuxPathValidator(String prefix, LanguageUtils langUtils) {
        super(prefix, langUtils);
    }

    protected ValidationResult validateAbsoluteLength(Path path) {
        // last check to print the warning only if everything else is correct

        final int maxPathLength = path.toString().length() + EAP_RESERVED_PATH_LENGTH;
        if (maxPathLength > LINUX_PATH_LENGTH_HARD_LIMIT) {
            return ValidationResult.error(getErrorMessage(ERROR_PATH_TOO_LONG, LINUX_PATH_LENGTH_HARD_LIMIT + ""));
        }
        return ValidationResult.ok();
    }

    protected ValidationResult validateCharacters(String installPathText) {

        for (String c : LINUX_INVALID_CHARACTERS) {
            if (installPathText.contains(c)) {
                return ValidationResult.error(getErrorMessage(INVALID_CHAR,
                        printIllegalCharacters(LINUX_INVALID_CHARACTERS_PRINT)));
            }
        }
        return ValidationResult.ok();
    }
}
