package com.yutou.bilibili.Tools;

import com.yutou.bilibili.BiliBili.Datas.DanmuData;
import com.yutou.bilibili.sqlite.BiliBiliLiveDatabasesManager;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DanmuTools {
    public static File danmuToAss(File live, File danmu, boolean useFileNameData, String... filterDanmu) {
        BiliBiliLiveDatabasesManager manager = new BiliBiliLiveDatabasesManager();
        try {
            FileTime creationTime = Files.readAttributes(Paths.get(live.getAbsolutePath()), BasicFileAttributes.class).creationTime();
            FileTime lastModifiedTime = Files.readAttributes(Paths.get(live.getAbsolutePath()), BasicFileAttributes.class).lastModifiedTime();
            Date startTime;
            if (useFileNameData) {
                startTime = getLiveDate(live.getName());
            } else {
                startTime = new Date(creationTime.toMillis());
            }
            manager.init(danmu);
            List<DanmuData> danmuData = manager.queryDanmu(startTime, new Date(lastModifiedTime.toMillis()));
            AssTools assTools = new AssTools(live.getName(), startTime);
            assTools.addFilter(filterDanmu);
            assTools.setAlpha(128);
            for (DanmuData danmuDatum : danmuData) {
                assTools.addDanmu(danmuDatum);
            }
            assTools.saveDanmu(live.getAbsolutePath().replace(live.getName().substring(live.getName().lastIndexOf(".")), ".ass"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            manager.close();
        }
        return null;
    }

    private static Date getLiveDate(String fileName) {
        Pattern pattern = Pattern.compile("(\\[.*\\]).");
        Matcher matcher = pattern.matcher(fileName);
        if (matcher.find()) {
            String str = matcher.group(1);
            try {
                return new SimpleDateFormat("[yyyy-MM-dd HHmmss]").parse(str);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        File live = new File("Z:\\download\\演唱会or录播\\2022年2月11日Liyuu_1st演唱会\\[2022-02-11 163454]5265.mp4");
        File danmu = new File("Z:\\download\\演唱会or录播\\2022年2月11日Liyuu_1st演唱会\\[2022-02-11]5265.db");
        danmuToAss(live, danmu,true, "老板大气！点点红包抽礼物！");
    }
}
