/*
 * 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;
import java.util.TreeSet;

/*
 * Note: we do not support DOS device paths https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths
 */
class WindowsPathValidator extends PathValidator {

    static final int WIN_PATH_LENGTH_SOFT_LIMIT = 259;
    static final int WIN_PATH_LENGTH_HARD_LIMIT = 32760;
    static final Set<String> WINDOWS_INVALID_CHARACTERS = Set.of("\0", "<", ">", ":", "\"", "//", "\\\\", "|", "?", "*", "  ", "%");
    private static final List<String> WINDOWS_INVALID_CHARACTERS_PRINT = List.of("'NUL'", "'<'", "'>'", "':'", "'\"'", "'//'", "'\\\\'", "'|'", "'?'", "'*'", "'%'");

    static final Set<String> WINDOWS_RESTRICTED_FILENAMES = new TreeSet<>(
            Set.of("CON", "PRN", "AUX", "NUL",
                    "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
                    "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"));

    WindowsPathValidator(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 > WIN_PATH_LENGTH_HARD_LIMIT) {
            return ValidationResult.error(getErrorMessage(ERROR_PATH_TOO_LONG, WIN_PATH_LENGTH_HARD_LIMIT + ""));
        } else if (maxPathLength > WIN_PATH_LENGTH_SOFT_LIMIT) {
            return ValidationResult.warning(getErrorMessage(WARN_PATH_TOO_LONG));
        }
        return ValidationResult.ok();
    }

    protected ValidationResult validateCharacters(String installPathText) {

        final int driveSeparatorIndex = installPathText.indexOf(":");
        if (driveSeparatorIndex > 1) {
            // drive part is not a single letter
            return ValidationResult.error(getErrorMessage(INVALID_CHAR,
                    printIllegalCharacters(WINDOWS_INVALID_CHARACTERS_PRINT)));
        }

        if (driveSeparatorIndex > 0) {
            installPathText = installPathText.substring(driveSeparatorIndex + 1);
        } else if (installPathText.startsWith("\\\\") || installPathText.startsWith("//")) {
            // ignore the leading double slash in UNC path
            installPathText = installPathText.substring(2);
        }

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

        // don't use File.separator - want to run those tests on Linux as well
        final String[] filenames = installPathText.split("(\\\\|/)");
        for (String filename : filenames) {
            if (WINDOWS_RESTRICTED_FILENAMES.contains(filename)) {
                return ValidationResult.error(getErrorMessage(RESTRICTED_FILENAME,
                        filename));
            }

        }
        return ValidationResult.ok();
    }
}
