package shop.alien.util.url;

import com.linkedin.urls.Url;
import com.linkedin.urls.detection.UrlDetector;
import com.linkedin.urls.detection.UrlDetectorOptions;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理url
 *
 * @author ssk
 * @version 1.0
 * @date 2022/12/27 13:33
 */
@Slf4j
public class UrlUtils {

    /**
     * 中文正则
     */
    private static String REGEX_CHINESE = "[\u4e00-\u9fa5]";

    /**
     * 从中文中获取链接
     *
     * @param content 内容
     * @return 保证只获取到一条抖音链接
     */
    public static String getUrl(String content) {
        StringBuilder urlStr = new StringBuilder();
        List<Url> found = parser(content);
        found = getLastUrl(found);
        for (Url url : found) {
            urlStr.append(url.getScheme());
            urlStr.append("://");
            urlStr.append(url.getHost());
            urlStr.append(url.getPath());
            if (urlStr.toString().contains("douyin")) {
                break;
            } else {
                urlStr = new StringBuilder();
            }
        }
        return urlStr.toString();
    }

    /**
     * 获取最后一个抖音链接
     *
     * @param urlList 链接List
     * @return list
     */
    private static List<Url> getLastUrl(List<Url> urlList) {
        int listSize = urlList.size();
        if (listSize > 1) {
            Url url = urlList.get(listSize - 1);
            StringBuilder urlStr = new StringBuilder();
            urlStr.append(url.getScheme());
            urlStr.append("://");
            urlStr.append(url.getHost());
            urlStr.append(url.getPath());
            if (urlStr.toString().contains("douyin")) {
                urlList = new ArrayList<>();
                urlList.add(url);
            }
        }
        return urlList;
    }

    /**
     * 提取链接
     *
     * @param text 文本
     * @return List<Url>
     */
    private static List<Url> parser(String text) {
        text = text.replaceAll(REGEX_CHINESE, " ");
        UrlDetector parser = new UrlDetector(text, UrlDetectorOptions.Default);
        return parser.detect();
    }

    public static String urlDecode(String str) {
        try {
            return URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        System.out.println(urlDecode("\u4e0a\u4f20\u6210\u529f"));
    }
}

