package com.zd.forward.serivce;


import com.zd.common.core.constant.HttpStatus;
import com.zd.common.core.domain.R;
import com.zd.common.core.exception.ServiceException;
import com.zd.forward.utils.VideoUtils;
import com.zd.system.api.RemoteFileService;
import com.zd.system.api.domain.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.rmi.ServerException;

import static com.zd.forward.utils.VideoUtils.frameToBufferedImage;

/**
 * @author hanson
 */
@Service
@Slf4j
public class ImageService {

    @Resource
    private RemoteFileService remoteFileService;

    /**
     * 生成的图片的类型
     */
    private static final String IMAGE_FORMAT = "jpg";

    public SysFile photograph(String streamUrl) throws IOException {
        try (FFmpegFrameGrabber grabber = VideoUtils.createGrabber(streamUrl)) {
            grabber.start();
            String fileName = "test";
            //文件储存对象
            File file = new File(fileName + "." + IMAGE_FORMAT);
            //获取第一帧
            Frame frame = grabber.grabFrame();
            if (frame != null) {
                //视频快照
                frame = grabber.grabImage();
                BufferedImage bufferedImage = frameToBufferedImage(frame);
                if (bufferedImage != null) {
                    ImageIO.write(bufferedImage, IMAGE_FORMAT, file);
                }
                log.info("图片地址为[{}]", file.getAbsoluteFile());
                grabber.stop();
                MultipartFile multipartFile = getMultipartFile(file);
                R<SysFile> upload = remoteFileService.upload(multipartFile);
                if (upload.getCode() == HttpStatus.SUCCESS && upload.getData() != null) {
                    return upload.getData();
                }else {
                    throw new ServerException(upload.getMsg());
                }
            }
        }
        return null;
    }

    private MultipartFile getMultipartFile(File file) {
        try(FileInputStream fileInputStream = new FileInputStream(file)) {
            return new MockMultipartFile(file.getName(),file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
