package com.sencorsta.rabs;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImageDownloader {
    public static void main(String[] args) {
        String inputFile = "D:\\Temp\\11111.txt";
        List<String> imageUrls = extractImageUrls(inputFile);

        if (imageUrls != null && !imageUrls.isEmpty()) {
            String downloadDirectory = "D:\\Temp\\downloaded-images"; // 本地保存图片的目录
            downloadImages(imageUrls, downloadDirectory);
        }
    }

    private static List<String> extractImageUrls(String inputFile) {
        List<String> imageUrls = new ArrayList<>();
        Pattern pattern = Pattern.compile("(https?://[^\"]+\\.png)");

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(line);
                while (matcher.find()) {
                    imageUrls.add(matcher.group(1));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return imageUrls;
    }

    private static void downloadImages(List<String> imageUrls, String downloadDirectory) {
        for (String imageUrl : imageUrls) {
            try {
                    String fileName = getFileNameFromUrl(imageUrl);
                    String filePath = StrUtil.join(File.separator, downloadDirectory, fileName);
                HttpUtil.downloadFile(imageUrl,filePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static String getFileNameFromUrl(String url) {
        int lastSlashIndex = url.lastIndexOf("/");
        if (lastSlashIndex != -1 && lastSlashIndex < url.length() - 1) {
            return url.substring(lastSlashIndex + 1);
        }
        return "unknown.png";
    }
}
