package net.northking.cctp.upperComputer.driver.agent.command;

import net.northking.cctp.upperComputer.driver.agent.command.protocol.AbstractProtocolCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.IOException;

public class TakeScreenshotCommand extends AbstractProtocolCommand<byte[]> {

    private final static Logger logger = LoggerFactory.getLogger(TakeScreenshotCommand.class);

    private static TakeScreenshotCommand instance = null;

    public static TakeScreenshotCommand getInstance() {
        if (instance == null) {
            instance = new TakeScreenshotCommand();
        }
        return instance;
    }

    @Override
    public int getCommandId() {
        return 33;
    }

    @Override
    public void doSend(DataOutput output) throws IOException {

    }

    @Override
    public byte[] buildReceive(DataInput input) throws IOException {
        int size = input.readInt();
        byte[] buffer = new byte[size];
        DataInputStream in = (DataInputStream) input;
        Thread currentThread = Thread.currentThread();
        long startTime = System.currentTimeMillis();
        int readCount = 0;
        while (!currentThread.isInterrupted() && readCount < size){
            if (in.available() > 0){
                readCount+=in.read(buffer,readCount,size-readCount);
            }else{
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    break;
                }
            }
            if (System.currentTimeMillis()-startTime > 1000){
                logger.error("读取截图数据超时");
                break;
            }
        }
        if (size!=readCount){
            logger.error("读取截图数据不完整，期望读取{}字节，超时时读取{}字节",size,readCount);
        }
        return buffer;
    }
}
