package com.ruixuan.data.service.impl;

import com.ruixuan.common.core.domain.ResultResponse;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.common.utils.file.FileUtil;
import com.ruixuan.data.service.VideoTextService;
import com.ruixuan.data.utils.VideoToPCMTool;
import com.ruixuan.data.utils.VoiceTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

@Slf4j
@Service
public class VideoTextServiceImpl implements VideoTextService {


    @Value("${pcm.local-path}")
    private String downloadPath;

    @Override
    public String getVideoText(String url) {
        if (Check.isNull(url)) {
            return null;
        }
        StringBuffer localPath = new StringBuffer();
        localPath.append(downloadPath).append("/").append("pcm").append("/").append(DateUtils.dateTime()).append("/");
        log.info("-------下载到服务器地址：{}", localPath.toString());
        String[] split = url.split("/");
        //本地文件内容
        String filePath = FileUtil.writeFiles(localPath.toString(), url, split[split.length - 1]);

        Path path = Paths.get(filePath);
        String pcmPath = null;

        // 获取 PCM path
        Optional<String> paths = VideoToPCMTool.convertMP4toPCM(path, Paths.get(localPath.toString()));
        String videoText = null;
        if (!Check.isNull(paths)) {
            pcmPath = paths.get();
            videoText = VoiceTool.getVideoText(pcmPath);
        }
        String finalPcmPath = pcmPath;
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10000);
                    File file = path.toFile();
                    if (file.exists()) {
                        file.delete();
                    }
                    File pcmFile = new File(finalPcmPath);
                    if (pcmFile.exists()) {
                        pcmFile.delete();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

        return videoText;
    }

}
