package org.aohe.webcam;

import lombok.extern.slf4j.Slf4j;
import org.aohe.constant.Control;
import org.aohe.constant.SocketEnum;
import org.aohe.web.SocketUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WebcamShowTask extends Thread {

    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    private String lastLog = "";

    @Override
    public void run() {
        scheduler.scheduleAtFixedRate(() -> {
            try {
                while (Control.SHOW_CAMERA) {
                    WebCamUtils.open();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    BufferedImage bi = WebCamUtils.getImage();
                    try {
                        ImageIO.write(bi, "JPG", baos);
                    } catch (IOException e) {
                        //log.error(e.getMessage(), e);
                    }finally {
                        if (bi != null){
                            bi.flush();
                            bi = null;
                        }
                    }
//                    String base64 = null;
//                    try {
//                        base64 = new String(Base64.getEncoder().encode(baos.toByteArray()), "UTF8");
//                    } catch (UnsupportedEncodingException e) {
//                        log.error(e.getMessage(), e);
//                    }finally {
//                        baos.close();
//                    }

                    SocketUtils.get(SocketEnum.CAM_SOCKET.getName()).broadcastNew(baos.toByteArray());
                    baos.close();
                }
            } catch (Exception e) {
                if(!lastLog.equals(e.getMessage())){
                    //相同的错误只打印一次
                    log.error(e.getMessage());
                    lastLog = e.getMessage();
                }
            }
        }, 0, 100, TimeUnit.MILLISECONDS);

        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            log.error("Main thread interrupted", e);
        }

    }

//    public static void main(String[] args) {
//        SocketUtils.start(SocketEnum.CAM_SOCKET);
//        WebCamUtils.setWebcam(0);
//        WebCamUtils.open();
//        //File file = new File("\"C:\\Users\\xxx\\Pictures\\Screenshots\\abc.png");
//        while (true){
//            SocketUtils.get(SocketEnum.CAM_SOCKET.getName()).broadcastNew(WebCamUtils.getImageByteBuffer());
//        }
//    }
}
