package com.artfess.file.util;

import com.artfess.base.util.AppUtil;
import com.artfess.base.util.FileUtil;
import com.artfess.file.config.FileUploadSetting;
import com.artfess.file.model.DefaultFile;
import com.artfess.file.persistence.manager.FlowUploadPropertiesManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class UploadM3u8 {


    public String uploadVideoToM3U8(DefaultFile defaultFile) {
        InputStream inputStream = null;
        if (DefaultFile.SAVE_TYPE_MINIO.equals(defaultFile.getStoreType())) {
            inputStream = MinioUtil.getMinioFile(null, defaultFile.getFilePath(), true);
        }
        // 获取上传视频的名称
        String filename = defaultFile.getFileName();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        // 为了保证视频在服务器中名字的唯一性，使用UUID来对filename进行改写
        String uuid = defaultFile.getId();
        FileUploadSetting fileUploadSetting = AppUtil.getBean(FileUploadSetting.class);
        String basepath = fileUploadSetting.getBasepath();
        String videoFilePath = basepath + File.separator + "video" + File.separator + date + File.separator + uuid + File.separator + filename;
        // 对这个文件进行上传操作
        try {
            File video = new File(videoFilePath);
            if (!video.exists()) {
                FileUtil.createFolder(videoFilePath, true);
                FileUtil.writeFile(videoFilePath, inputStream);
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        File m3u8 = new File(basepath + File.separator + "video" + File.separator + date + File.separator + uuid + File.separator + defaultFile.getId() + ".m3u8");
        try {
            m3u8.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //m3u8分片编码,使用FFmpeg将视频分成多个小块
        //被注释的这个快一点
        //片段时间(秒)
        log.info("videoFilePath：{},m3u8Path:{}",videoFilePath, m3u8.getPath());
        String hls_time = "10";
        ProcessBuilder pb = new ProcessBuilder("ffmpeg", "-i", videoFilePath, "-codec", "copy", "-start_number", "0", "-hls_time", hls_time, "-hls_list_size", "0", "-f", "hls", m3u8.getPath());
//        ProcessBuilder pb = new ProcessBuilder("ffmpeg", "-i", videoFilePath, "-force_key_frames", "expr:gte(t,n_forced*1)", "-strict", "-2", "-c:a", "aac", "-c:v", "libx264",
//                "-hls_time", hls_time, "-hls_list_size", "0", "-f", "hls", m3u8.getPath());
        // 将标准错误流和标准输出流合并
        pb.redirectErrorStream(true);

        Process p = null;
        try {
            p = pb.start();
            // 处理FFmpeg的输出信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
            log.error("视频转换失败：fileId:{},失败错误信息：{}", defaultFile.getId(), e.getMessage());
        }
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String tempUrl = "/m3u8/video" + File.separator + date + File.separator + uuid + File.separator + defaultFile.getId() + ".m3u8";
        return tempUrl.replace("\\", "/");
    }

}
