package cn.bunny.starTrek;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StarTrekWithDiscovery {
    // 字幕文件目录
    private static final Path SUBTITLE_PATH = Path.of("G:\\媒体\\电视剧\\星际迷航系列\\星际迷航：发现号系列\\字幕");

    // 输出文件目录
    private static final Path OUTPUT_PATH = Path.of("F:\\学习\\代码\\Java\\完成字幕");

    // 匹配字幕中英文正则表达式
    private static final Pattern LINE_PATTERN = Pattern.compile("Dialogue: .*,,(?<chinese>.*?)\\\\.*?}(?<english>.*)");

    public static void main(String[] args) throws IOException {
        // 先删除所有文件
        deleteFolder(new File(OUTPUT_PATH.toString()));

        // 递归查找需要文件内容
        try (Stream<Path> walk = Files.walk(SUBTITLE_PATH)) {
            walk.filter(file -> file.getFileName().toString().endsWith("ass"))
                    .forEach(StarTrekWithDiscovery::processFile);
        } catch (IOException e) {
            throw new RuntimeException("Error processing files", e);
        }
    }

    /**
     * 文件进程
     *
     * @param file 文件
     */
    private static void processFile(Path file) {
        // 相对路径
        Path relativePath = SUBTITLE_PATH.relativize(file.getParent());

        // 输出文件目录
        Path outputDir = OUTPUT_PATH.resolve(relativePath);

        try (Stream<String> lines = Files.lines(file, StandardCharsets.UTF_8)) {
            Files.createDirectories(outputDir);

            String content = lines.map(line -> {
                        // 匹配需要的字幕内容
                        Matcher matcher = LINE_PATTERN.matcher(line);

                        if (matcher.find()) {
                            String chinese = matcher.group("chinese");
                            String english = matcher.group("english");
                            return chinese + "   " + english;
                        }
                        return null;
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining("\n"));

            Files.writeString(outputDir.resolve(file.getFileName()), content, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException("Error processing file: " + file, e);
        }
    }

    /**
     * 删除文件
     *
     * @param folder 文件目录
     */
    public static void deleteFolder(File folder) {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteFolder(file);
                }
            }
        }
        boolean delete = folder.delete();
        System.out.println("删除文件" + folder.getName() + "：" + (delete ? "成功" : "失败"));
    }
}
