package org.aohe.daemon;

import lombok.extern.slf4j.Slf4j;
import org.aohe.constant.Control;
import org.aohe.constant.SocketEnum;
import org.aohe.web.SocketServer;
import org.aohe.web.SocketUtils;
import org.aohe.webcam.WebCamUtils;
import org.aohe.webcam.WebcamShowTask;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static org.aohe.constant.Control.WEBCAM_SHOW_TASK;
@Slf4j
public class WatchDog extends Thread{

    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    public void run() {
        scheduler.scheduleAtFixedRate (() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SocketServer camSocket = SocketUtils.get(SocketEnum.CAM_SOCKET.getName());
            //清理拍照资源
            if(camSocket == null || camSocket.getConnections().isEmpty()){
                if(!Control.SHOW_CAMERA){
                    //图片传输循环未关闭
                    WebCamUtils.closeWebcamTransfer();
                }
            }
            if(WEBCAM_SHOW_TASK == null || !WEBCAM_SHOW_TASK.isAlive()){
                System.gc();
                WEBCAM_SHOW_TASK = new WebcamShowTask();
                WEBCAM_SHOW_TASK.start();
            }
        }, 0, 100, TimeUnit.MILLISECONDS);

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