package top.octopusyan.utils;

import top.octopusyan.config.ProxyConfig;
import top.octopusyan.manager.http.request.ProxySetup;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author : octopus yan
 * @email : octopus_yan@foxmail.com
 * @description :
 * @create : 2022-4-6 20:57
 */
public class DomainUtil {

    public static String getCustomize(ProxySetup setup) {
        String domain = setup.getDomain();
        String serverPath = getServerPath(setup);
        int end = domain.indexOf("." + serverPath);
        if (domain.length() <= 0 || end == -1) return "";
        return domain.substring(0, end);
    }

    public static String getSuffix(ProxySetup setup) {
        String serverPath = getServerPath(setup);
        return "." + serverPath;
    }

    /**
     * 是否自定义隧道
     */
    public static boolean isCustomize(ProxySetup setup) {
        return !setup.getDomain().contains(getServerPath(setup));
    }

    public static boolean isCustomize(ProxySetup setup, String serverName) {
        return !setup.getDomain().contains(ProxyConfig.getServerPath(serverName));
    }

    private static String getServerPath(ProxySetup setup) {
        return ProxyConfig.getServerPath(ProxyConfig.getServerName(setup.getNode()));
    }

    public static String getDomainAddress(String domain) {
        try {
            return InetAddress.getByName(domain).getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }
    }
}
