package org.jeecg.modules.adweb.common.util;

import static java.util.function.Predicate.*;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.net.InternetDomainName;

import lombok.extern.slf4j.Slf4j;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * 常用工具类
 *
 * @author wfansh
 */
@Slf4j
public class CommonUtil {

    /**
     * 解析URL的顶级域名
     *
     * @param url 例如 https://www.essaynerdie.com, www.essaynerdie.com,
     *     https://www.essaynerdie.com/products
     * @return essaynerdie.com
     */
    public static String getTopPrivateDomain(String url) {
        String host = url;
        try {
            host = new URL(url).getHost();
        } catch (MalformedURLException e) {
        } finally {
            return InternetDomainName.from(host).topPrivateDomain().toString();
        }
    }

    /**
     * 对一个字符串进行split and trim，过滤空串，返回{@link List}
     *
     * @param str
     * @param separator
     * @return
     */
    public static List<String> splitAndTrim(String str, final String separator) {
        return Splitter.on(separator)
                .splitToStream(str)
                .map(String::trim)
                .filter(not(Strings::isNullOrEmpty))
                .toList();
    }
}
