package ink.wgink.module.file.media.task.transcoding;

import ink.wgink.module.file.media.pojo.dtos.ConvertProgressDTO;
import ink.wgink.module.file.media.task.transcoding.runnable.VideoConvertRunnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.*;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: VideoTransCodingManager
 * @Description: 视频转码
 * @Author: wanggeng
 * @Date: 2021/6/10 9:46 上午
 * @Version: 1.0
 */
public class VideoConvertManager {
    private static final Logger LOG = LoggerFactory.getLogger(VideoConvertManager.class);
    private static VideoConvertManager VIDEO_TRANS_CODING_MANAGER = VideoTransCodingManagerBuilder.videoConvertManager;
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10, 30L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
    private Map<String, SseEmitter> convertProgressSseEmitterMap = new ConcurrentHashMap<>();

    private VideoConvertManager() {
    }

    public static VideoConvertManager getInstance() {
        return VIDEO_TRANS_CODING_MANAGER;
    }

    public void convert(VideoConvertRunnable videoConvertRunnable) {
        threadPoolExecutor.execute(videoConvertRunnable);
    }

    public void addConvertProgressSseEmitter(String sseEmitterId, SseEmitter sseEmitter) {
        convertProgressSseEmitterMap.put(sseEmitterId, sseEmitter);
        // 发送空对象
        ConvertProgressDTO convertProgressDTO = new ConvertProgressDTO();
        convertProgressDTO.setFileId("");
        convertProgressDTO.setPercent(0D);
        try {
            sseEmitter.send(convertProgressDTO);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public void removeConvertProgressSseEmitter(String sseEmitterId) {
        convertProgressSseEmitterMap.remove(sseEmitterId);
    }

    public void convertProgressSseEmitterNotice(String fileId, Double percent) {
        ConvertProgressDTO convertProgressDTO = new ConvertProgressDTO();
        convertProgressDTO.setFileId(fileId);
        convertProgressDTO.setPercent(percent);
        LOG.debug("视频ID {} 转码进度：{}%", fileId, percent);
        for (Map.Entry<String, SseEmitter> kv : convertProgressSseEmitterMap.entrySet()) {
            try {
                kv.getValue().send(convertProgressDTO);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    private static class VideoTransCodingManagerBuilder {
        public static VideoConvertManager videoConvertManager = new VideoConvertManager();
    }

}
