package com.yutou.nas.Services.impl;

import com.alibaba.fastjson2.JSONObject;
import com.yutou.nas.Services.IVideoToolsService;
import com.yutou.nas.bangumi.BangumiTools;
import com.yutou.nas.interfaces.ObjectInterface;
import com.yutou.nas.mybatis.dao.VideoDataDao;
import com.yutou.nas.mybatis.dao.VideoInfoDao;
import com.yutou.nas.mybatis.dao.VideoSubtitlesDao;
import com.yutou.nas.mybatis.model.VideoData;
import com.yutou.nas.mybatis.model.VideoInfo;
import com.yutou.nas.mybatis.model.VideoInfoExample;
import com.yutou.nas.mybatis.model.VideoSubtitles;
import com.yutou.nas.utils.AppTools;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

@Service("VideoToolsService")
public class VideoToolsService implements IVideoToolsService {


    @Resource
    VideoInfoDao infoDao;
    @Resource
    VideoDataDao dataDao;
    @Resource
    VideoSubtitlesDao subtitlesDao;

    @Override
    public void scanVideo() {
        scanVideoDir(new File("Z:\\download\\anim\\打了300年的史莱姆，不知不觉就练到了满级"));
        scanVideo(new File("Z:\\download\\anim\\打了300年的史莱姆，不知不觉就练到了满级"));
        List<VideoInfo> videoInfos = videoDirInfo(new File("Z:\\download\\anim\\打了300年的史莱姆，不知不觉就练到了满级"));
        for (VideoInfo videoInfo : videoInfos) {
            System.out.println(videoInfo.getTitleCn());
        }
        System.out.println("输入新番信息：");
        String name = "一弦定音！第二季";
        for (VideoInfo videoInfo : videoInfos) {
            if (videoInfo.getId() == 292969) {
                VideoInfoExample example = new VideoInfoExample();
                example.createCriteria().andTitleCnEqualTo("打了300年的史莱姆，不知不觉就练到了满级");
                VideoInfo info = infoDao.selectByExample(example).get(0);
                videoInfo.setId(info.getId());
                videoInfo.setPath(info.getPath());
                infoDao.updateByPrimaryKey(videoInfo);
            }
            if (videoInfo.getId() == 270060) {
                VideoInfoExample example = new VideoInfoExample();
                example.createCriteria().andTitleCnEqualTo("s2");
                VideoInfo info = infoDao.selectByExample(example).get(0);
                videoInfo.setId(info.getId());
                videoInfo.setPath(info.getPath());
                infoDao.updateByPrimaryKey(videoInfo);
            }
        }
    }

    public void scanVideoDir(File dirPath) {
        int dirCount = 0;
        for (File file : dirPath.listFiles()) {
            if (file.isDirectory()) {
                VideoInfo info = new VideoInfo();
                info.setTitleCn(file.getName());
                info.setPath(file.getAbsolutePath());
                infoDao.insert(info);
                dirCount++;
            }
        }
        if (dirCount != dirPath.listFiles().length) {
            VideoInfo info = new VideoInfo();
            info.setTitleCn(dirPath.getName());
            info.setPath(dirPath.getAbsolutePath());
            infoDao.insert(info);
        }
    }

    public void scanVideo(File dir) {
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                scanVideo(file);
            } else {
                if (file.getName().endsWith(".mp4")
                        || file.getName().endsWith("mkv")
                ) {
                    VideoInfoExample example = new VideoInfoExample();
                    example.createCriteria().andPathEqualTo(dir.getAbsolutePath());
                    videoInfo(infoDao.selectByExample(example).get(0).getId(), file);
                }
            }
        }
    }

    private void videoInfo(int vid, File file) {
        AppTools.exec("ffmpeg -i \"" + file.getAbsolutePath() + "\"", new ObjectInterface() {
            @Override
            public void out(String data) {
                super.out(data);
                String[] ffmpegData = data.split("\n");
                Map<String, String> map = new LinkedHashMap<>();
                for (String ffmpegDatum : ffmpegData) {
                    if (ffmpegDatum.trim().startsWith("Stream #")) {
                        String[] metadata = ffmpegDatum.split(": ");
                        map.put(metadata[0].trim() + "_" + metadata[1], metadata[2]);
                    }
                    if (ffmpegDatum.trim().startsWith("Duration: ")) {
                        map.put("Duration", ffmpegDatum.replace("Duration: ", "").trim().split("\\,")[0]);
                    }
                }
                //System.out.println(data);
                VideoData videoData = new VideoData();
                videoData.setVid(vid);
                videoData.setPath(file.getAbsolutePath());
                videoData.setFiletitle(file.getName());
                videoData.setIsplay(0);
                videoData.setLastplaytime("00:00:00");
                for (String key : map.keySet()) {
                    System.out.println("vid = " + vid + " file = " + file.getName() + " key = " + key + " value = " + map.get(key));
                    if (key.endsWith("Video")) {
                        videoData.setVideodata(map.get(key));
                    }
                    if (key.endsWith("Audio")) {
                        videoData.setSounddata(map.get(key));
                    }
                    if ("Duration".equals(key)) {
                        videoData.setVideotimer(map.get(key));
                    }
                }
                dataDao.insert(videoData);
                for (String key : map.keySet()) {
                    if (key.endsWith("Subtitle")) {
                        String code = key.replace("Stream #", "").split("\\(")[0];
                        String title = key.replace("Stream #" + code, "")
                                .split("_Subtitle")[0]
                                .replace("(", "")
                                .replace(")", "");
                        new SubtitleTrack().outFFMpegSubtitle(videoData.getId(), code, title, file);
                    }
                }

            }
        }, false, false);
    }

    public class SubtitleTrack {
        private void outFFMpegSubtitle(int id, String code, String title, File file) {
            if (new File(file.getAbsolutePath() + "." + title + ".srt").exists()) {
                new File(file.getAbsolutePath() + "." + title + ".srt").deleteOnExit();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String exec = "ffmpeg -i \"" + file.getAbsolutePath() + "\" -vn -an -map " + code + " \"" + file.getAbsolutePath() + "." + title + ".srt\"";
                    System.out.println("exec = " + exec);
                    AppTools.exec(exec + "\n", new ObjectInterface() {
                        @Override
                        public void out(String data) {
                            super.out(data);
                            System.out.println("保存字幕文件:" + title);
                            VideoSubtitles subtitles = new VideoSubtitles();
                            subtitles.setVid(id);
                            subtitles.setPath(file.getAbsolutePath() + "." + title + ".srt");
                            subtitles.setSubtitle(title);
                            subtitlesDao.insert(subtitles);
                        }
                    }, false, false);

                }
            }).start();
        }
        public void selectFile(int id,String code,File sub){

        }
    }


    private List<VideoInfo> videoDirInfo(File file) {
        List<VideoInfo> videoInfos = new ArrayList<>();
        JSONObject main = BangumiTools.search(file.getName());
        if (main.getInteger("results") > 0) {
            List<JSONObject> list = main.getJSONArray("list").toJavaList(JSONObject.class);
            Collections.reverse(list);
            for (JSONObject item : list) {
                VideoInfo info = new VideoInfo();
                info.setId(item.getInteger("id"));
                info.setTitleCn(item.getString("name_cn"));
                info.setTitleJp(item.getString("name"));
                info.setAirData(item.getString("air_date"));
                info.setAirWeekday(item.getInteger("air_weekday") + "");
                info.setBangumiRating(Double.valueOf(item.getJSONObject("rating").getFloat("score")));
                info.setBangumiUrl(item.getString("url"));
                info.setEpsCount(item.getInteger("eps") + "");
                info.setEpsNow("0");
                if (item.containsKey("crt")) {
                    info.setCrts(item.getJSONArray("crt").toJSONString());
                }
                if (item.containsKey("staff")) {
                    info.setStaffs(item.getJSONArray("staff").toJSONString());
                }
                info.setImage(item.getJSONObject("images").getString("large"));
                info.setInfo(item.getString("summary"));
                info.setPath(file.getAbsolutePath());
                videoInfos.add(info);
            }
        }
        return videoInfos;
    }

    public static void main(String[] args) {
        // videoInfo(0,new File("Z:\\download\\anim\\小林家的龙女仆S\\[NC-Raws] 小林家的龙女仆S - 01 [B-Global][WEB-DL][2160p][AVC AAC][CHS_CHT_ENG_TH_SRT][MKV].mkv"));
        //videoDirInfo(new File("Z:\\download\\anim\\小林家的龙女仆S\\"));
      /*  List<VideoInfo> list = videoDirInfo(new File("Z:\\download\\anim\\小林家的龙女仆S\\"));
        for (VideoInfo videoInfo : list) {
            System.out.println(videoInfo.getTitle());
        }*/
    }
}
