/*******************************************************************************
 * Copyright (c) 2024-2025 R3944Realms. All rights reserved.
 * <p>
 * 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
 * <p>
 *     http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 com.r3944realms.dg_lab.utils.stringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The type Url validator.
 */
public class UrlValidator {
    private static final String DOMAIN_REGEX = "^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$";
    private static final String IP_REGEX = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";

    private static final Pattern DOMAIN_PATTERN = Pattern.compile(DOMAIN_REGEX);
    private static final Pattern IP_PATTERN = Pattern.compile(IP_REGEX);

    /**
     * Is valid address boolean.
     *
     * @param address the address
     * @return the boolean
     */
    public static boolean isValidAddress(String address) {
        return isValidDomain(address) || isValidIP(address);
    }

    private static boolean isValidDomain(String domain) {
        String[] parts = domain.split("\\.");
        if (parts.length < 2) {
            return false;
        }
        for (String part : parts) {
            Matcher matcher = DOMAIN_PATTERN.matcher(part);
            if (!matcher.matches()) {
                return false;
            }
        }
        return true;
    }

    private static boolean isValidIP(String ip) {
        Matcher matcher = IP_PATTERN.matcher(ip);
        return matcher.matches();
    }

    /**
     * Is valid port boolean.
     *
     * @param Port the port
     * @return the boolean
     */
    public static boolean isValidPort(int Port) {
        return Port >= 0 && Port <= 65535;
    }
}
