package net.northking.cctp.upperComputer.webSocket.thread;

import com.alibaba.fastjson.JSON;
import net.northking.cctp.upperComputer.deviceManager.UpperComputerManager;
import net.northking.cctp.upperComputer.enums.FileBusinessTypeEnum;
import net.northking.cctp.upperComputer.entity.Attachment;
import net.northking.cctp.upperComputer.utils.HttpUtils;
import net.northking.cctp.upperComputer.utils.ProcessCmdUtils;
import net.northking.cctp.upperComputer.utils.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 录屏线程
 */
public class AndroidScreenRecordThread extends Thread{

    private Logger logger = LoggerFactory.getLogger(AndroidScreenRecordThread.class);

    private String serial;

    private Process process;

    private String recordFileName;

    private String tenantId;

    private int videoWidth;

    private int videoHeight;

    public AndroidScreenRecordThread(String serial,String tenantId,int width,int height){
        this.serial = serial;
        this.tenantId = tenantId;
        this.videoWidth = width;
        this.videoHeight = height;
        setName("[" + serial+"]-record");
    }

    @Override
    public void run() {
        String applicationPath = UpperComputerManager.getInstance().getApplicationPath();
        applicationPath = applicationPath.replace("\\","/");
        File screenRecordPath = new File(applicationPath + "/screenRecordTmp/");
        if (!screenRecordPath.exists()) {
            screenRecordPath.mkdirs();
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String dateFormat = format.format(new Date());
        String tmpPath = screenRecordPath.getAbsolutePath();
        tmpPath = tmpPath.replace("\\","/");
        recordFileName = tmpPath + "/" + serial + "_" + dateFormat + ".mp4";
        List<String> cmdList = new ArrayList<>();
        cmdList.add("scrcpy");
        cmdList.add("-s");
        cmdList.add(serial);
        cmdList.add("-b");
        cmdList.add("2M");
        cmdList.add("-Nr");
        cmdList.add(recordFileName);
        logger.info("[" +serial+ "]录屏开启，时间:{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        process = ProcessCmdUtils.execCmd(cmdList);
        InputStreamReader ir = null;
        LineNumberReader input = null;
        try {
            ir = new InputStreamReader(process.getInputStream(),"UTF-8");
            input = new LineNumberReader(ir);
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = input.readLine()) != null) {
                logger.debug(line);
                sb.append(line);
            }
            input.close();
        } catch (Exception e) {
            logger.warn("读取录屏输出失败",e);
        }
        logger.info("[" +serial+ "]录屏结束，时间:{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    public String stopRecord(){
        if (null != process) {
            process.destroy();
            logger.debug("录屏进程是否存活：{}",process.isAlive());
            //上传文件
            logger.debug("[" +serial+ "]录屏停止，开始上传视屏文件");
            String serverAddress = SpringUtils.getProperties("nk.mobile-computer.serverAddr");
            String pubUploadPath = SpringUtils.getProperties("nk.mobile-computer.publicUploadAddr");
            try {
                if (StringUtils.isNotBlank(recordFileName)) {
                    File file = new File(recordFileName);
                    //文件存在才上传
                    if (null != file && file.exists()) {
                        logger.info("开始上传安卓视频文件，设备Id：{}", serial);
                        Attachment upload = HttpUtils.upload(serverAddress + pubUploadPath, recordFileName, tenantId, null, FileBusinessTypeEnum.MOBILE_TASK_VIDEO.getCode());
                        if (null != upload && StringUtils.isNotBlank(upload.getId())) {
                            logger.debug("文件上传成功，返回id：{}", upload.getId());
                            Map<String, String> resultMap = new HashMap<>();
                            resultMap.put("videoUrl", upload.getUrlPath());
                            resultMap.put("videoRef", videoWidth + "x" + videoHeight);
                            return JSON.toJSONString(resultMap);
                        }
                    }
                }else {
                    logger.warn("[" +serial+ "]录屏文件路径为空");
                }
            }catch (Exception e) {
                logger.error("上传录像文件异常，",e);
            }
        }
        return null;
    }

    public void killRecord(){
        if (null != process) {
            process.destroy();
            logger.debug("原录屏进程是否存活：",process.isAlive());
            File file = new File(recordFileName);
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
