package com.yida.data.device.camera.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.yida.data.system.feign.RemoteCommonService;
import javafx.application.Application;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.*;
import org.bytedeco.javacv.Frame;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;

@Slf4j
@RequiredArgsConstructor
@Component
public class RecordVideoStream{

    private final RemoteCommonService commonService;

    /**
     * 获取直播第一帧
     * @param streamURL  直播拉流路径
     */
    public String getFirstPicByStream(String streamURL){

        //String streamURL="rtmp://xxx.xxxxx.com/appName/1591250292?auth_key=1591252092-0-0-e996f5d75ca9c86fb57c9e3a3cb47bf4";

        ApplicationHome applicationHome = new ApplicationHome(getClass());

        File directory = new File( applicationHome.getSource().getPath());

        File file = null;
        try {
            file = File.createTempFile("temp", ".jpg", directory);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }

        System.out.println(file.getAbsolutePath());


        String url = "";
        // 获取视频源
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(streamURL);
        try {
            grabber.start();
            int ftp = grabber.getLengthInFrames();
            int flag=0;
            Frame frame = null;
            while (flag <= ftp) {
                //获取帧
                frame = grabber.grabImage();
                //过滤前3帧，避免出现全黑图片
                if ((flag>3)&&(frame != null)) {
                    break;
                }
                flag++;
            }
            FrameToBufferedImage(frame, file);
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int)file.length()];
            inputFile.read(buffer);
            inputFile.close();
            String encode = new BASE64Encoder().encode(buffer);
            url = commonService.uploadImg(encode).getData();
        } catch (FrameGrabber.Exception e) {
            log.error("获取视频第一帧异常:{}",e.getMessage());
        }  catch (IOException e) {
            log.error("获取视频第一帧异常:{}",e.getMessage());
        } finally {
            try {
                grabber.stop();
                file.deleteOnExit();
            } catch (FrameGrabber.Exception e) {
                e.printStackTrace();
            }
        }
        return url;
    }

    private static void FrameToBufferedImage(Frame frame,File file) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage fecthedImage = converter.getBufferedImage(frame);
        BufferedImage bi = new BufferedImage(780, 390, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(fecthedImage.getScaledInstance(780, 390, Image.SCALE_SMOOTH),0, 0, null);
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        try {
            ImageIO.write(bi, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}


