package net.northking.cctp.upperComputer.utils;

import net.northking.cctp.upperComputer.deviceManager.AndroidDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.thread.AndroidDeviceInitThread;
import net.northking.cctp.upperComputer.driver.adb.Adb;
import net.northking.cctp.upperComputer.driver.adb.AdbDevice;
import net.northking.cctp.upperComputer.driver.adb.AdbTransport;
import net.northking.cctp.upperComputer.exception.ExecuteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Date;
import java.util.Map;

/**
 * @author : yineng.huang
 * @date : 2022/7/18 16:54
 */
public class ScreenShotUtils {

    private final static Logger log = LoggerFactory.getLogger(ScreenShotUtils.class);

    private final static String SCREEN_CMD = "tidevice -u %s screenshot %s";

    public static File getMobileScreenShot(String deviceId, String resolution, boolean overTurn) {
        String picPath = null;
        //获取分辨率
        String[] split = resolution.split("\\*");
        int small = Integer.parseInt(split[0]);
        int large = Integer.parseInt(split[1]);
        int isBigger = Integer.parseInt(split[0]) - Integer.parseInt(split[1]);
        if (isBigger > 0) {
            large = large + isBigger;
            small = small - isBigger;
        }
        String vm_size = "";
        AndroidDeviceInitThread initThread = AndroidDeviceManager.getInstance().getAndroidInitThread(deviceId);
        Map<String, Integer> realScreenSize = initThread.getRealScreenSize();
        if (null == realScreenSize) {
            if (overTurn) {
                vm_size = large + "x" + small;
            } else {
                vm_size = small + "x" + large;
            }
        } else {
            log.warn("走的是上位机获取设备宽高。。。。。。。。。。。。。。。。");
            vm_size = realScreenSize.get("width") + "x" + realScreenSize.get("height");
        }
        log.info("截图的设备参数,长宽:{}",vm_size);

        String fileName = "/sdcard/" + new Date().getTime() + ".jpg";
        File cutFilePath = new File(System.getProperty("user.dir") + "/tempPic");
        if (!cutFilePath.exists()) {
            cutFilePath.mkdirs();
        }
        Adb adb = AndroidDeviceManager.getInstance().getAdb();
        AdbDevice adbDevice = AndroidDeviceManager.getInstance().getCurrentDevice(deviceId);
        AdbTransport transport = adb.shell(adbDevice, String.format("export CLASSPATH=/data/local/tmp/minicap.apk;app_process /system/bin  io.devicefarmer.minicap.Main -P %s@%s/0 -s > %s", vm_size, vm_size, fileName));
        String line = null;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(transport.getInputStream()));
            while ((line = reader.readLine()) != null) {
                log.debug(line);
            }
        } catch (Exception e) {
            log.error("截图失败", e);
            throw new ExecuteException("截图失败");
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("reader关闭失败，e",e);
                }
            }
            if (null != transport) {
                try {
                    transport.close();
                } catch (IOException e) {
                    log.error("transport关闭失败，e",e);
                }
            }
        }
        //拉取图片
        String localPath = cutFilePath.getAbsolutePath() + "/" + System.currentTimeMillis() + ".png";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(localPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        boolean pullOk = adb.pull(adbDevice, fileOutputStream, fileName);
        if (!pullOk) {
            log.debug("拉取图片失败");
            throw new ExecuteException("拉去图片失败");
        }
        //删除手机图片
        adb.shell(adbDevice, String.format("rm %s", fileName));
        File file = new File(localPath);
        return file;
    }

    public static File getIOSMobileScreenShot(String deviceId) {
        File cutFilePath = new File(System.getProperty("user.dir") + "/tempPic");
        if (!cutFilePath.exists()) {
            cutFilePath.mkdirs();
        }
        String localPic = cutFilePath.getAbsolutePath() + "/" + System.currentTimeMillis() + ".png";
        String[] cmd = {"tidevice", "-u", deviceId, "screenshot", localPic};
        ProcessBuilder builder = new ProcessBuilder(cmd).redirectErrorStream(true);
        try {
            Process start = builder.start();
            start.waitFor();
        } catch (IOException e) {
            log.error("截图失败", e);
            throw new ExecuteException("截图失败");
        } catch (InterruptedException e) {
            log.error("线程异常中断，e",e);
            Thread.currentThread().interrupt();
        }
        File file = new File(localPic);
        return file;

    }
}
