/*
 * Copyright 2022 Red Hat, Inc. and/or its affiliates
 * and other 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.FileUtils;
import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.ValidationResult;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;

public class MavenRepositoryValidator {

    public static final String REPO_PATH_EMPTY_KEY = "quickstarts.maven.setup.repo_path_empty_error";

    public static final String REMOTE_REPO_PATH_ERROR_KEY = "quickstarts.maven.setup.remote_repo_path_error";
    public static final String LOCAL_REPO_PATH_ERROR_KEY = "quickstarts.maven.setup.local_repo_path_error";

    private static final List<String> REMOTE_PROTOCOLS = Arrays.asList("http", "https");
    private final LanguageUtils languageUtils;

    public MavenRepositoryValidator(LanguageUtils languageUtils) {
        this.languageUtils = languageUtils;
    }

    public ValidationResult validate(String path) {
        if (path == null) {
            return ValidationResult.error(languageUtils.getString(REPO_PATH_EMPTY_KEY));
        }
        if (isRemoteProtocol(path)) {
            if (!remoteFileExists(path)) {
                return ValidationResult.error(languageUtils.getString(REMOTE_REPO_PATH_ERROR_KEY));
            }
        } else {
            try {
                final File repoFile;
                if (FileUtils.isUrl(path)) {
                    repoFile = Path.of(new URL(path).toURI()).toFile();
                } else {
                    repoFile = Path.of(path).toAbsolutePath().toFile();
                }
                if (!repoFile.exists() || !repoFile.isDirectory()) {
                    return ValidationResult.error(languageUtils.getString(LOCAL_REPO_PATH_ERROR_KEY));
                }

            } catch (URISyntaxException | MalformedURLException e) {
                throw new RuntimeException(e);
            } catch (InvalidPathException e) {
                return PathValidator.newInstance("generic", languageUtils).validate(path);
            }
        }
        return ValidationResult.ok();
    }

    public static boolean isRemoteProtocol(String path) {
        for (String protocol : REMOTE_PROTOCOLS) {
            if (path.startsWith(protocol)) {
                return true;
            }
        }
        return false;
    }

    public boolean remoteFileExists(String url) {
        try {
            HttpURLConnection.setFollowRedirects(true);
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("HEAD");
            return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
        } catch (Exception e) {
            return false;
        }
    }

    LanguageUtils getLanguageUtils() {
        return languageUtils;
    }
}
