package net.northking.cctp.upperComputer.utils.deviceHepler.android;

import net.northking.cctp.upperComputer.deviceManager.AndroidDeviceManager;
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 net.northking.cctp.upperComputer.utils.deviceHepler.AbstractDeviceHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author : yineng.huang
 * @date : 2024/11/11 11:13
 */
public class AndroidDeviceHelper extends AbstractDeviceHelper {

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

    @Override
    public boolean cleanData(String deviceId, String appPackage) {
        boolean success = false;
        logger.info("Clean data for app[{}] on device[{}]", appPackage, deviceId);
        Adb adb = AndroidDeviceManager.getInstance().getAdb();
        AdbDevice adbDevice = AndroidDeviceManager.getInstance().getCurrentDevice(deviceId);
        if (null == adbDevice) {
            logger.error("设备【{}】不在线", deviceId);
            return false;
        }
        AdbTransport adbTransport = adb.shell(adbDevice, String.format("pm clear %s ", appPackage));
        String line = null;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(adbTransport.getInputStream()));
            while ((line = reader.readLine()) != null) {
                logger.debug(line);
                if (line.contains("Success")) {
                    success = true;
                }
            }
        } catch (Exception e) {
            logger.error("清除数据失败", e);
            return false;
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != adbTransport) {
                try {
                    adbTransport.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    @Override
    public boolean isAppInstalled(String deviceId, String appPackage) {
        return false;
    }

    @Override
    public boolean removeApp(String deviceId, String appPackage) {
        return false;
    }

    @Override
    public boolean terminateApp(String deviceId, String appPackage) {
        AdbDevice currentDevice = AndroidDeviceManager.getInstance().getCurrentDevice(deviceId);
        if (null == currentDevice) {
            throw new ExecuteException("设备不在线，无法启动app");
        }
        Adb adb = AndroidDeviceManager.getInstance().getAdb();
        if (adb == null) {
            try {
                adb = new Adb();
            } catch (IOException e) {
                logger.warn("adb通信出现错误", e);
                return false;
            }
        }
        AdbTransport shell = adb.shell(currentDevice, "am force-stop " + appPackage);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
            String line = null;
            while (null != (line = reader.readLine())) {
                logger.debug("设备【{}】关闭应用打印：{}", deviceId, line);
            }
            return true;
        } catch (IOException e) {
            logger.warn("启动app出现错误", e);
        }
        return false;
    }

    @Override
    public String getOldPackageCode(String deviceId, String appPackage) {
        String oldPackageCode = "";
        String shell = "adb -s " + deviceId + " shell dumpsys package " + appPackage + " |grep versionName";
        try {
            Process process = Runtime.getRuntime().exec(shell);
            process.waitFor();
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = in.readLine();
            if (StringUtils.isNotBlank(line)) {
                oldPackageCode = line.split("=")[1];
            }
        } catch (Exception e) {
            logger.error("获取应用版本失败", e);
        }
        logger.debug("手机应用版本为:" + oldPackageCode);
        return oldPackageCode;
    }

    @Override
    public boolean installApp(String deviceId, String appPath) {
        logger.debug("收到设备【{}】安装应用【{}】的请求",deviceId,appPath);
        String[] installAppCmd = {"adb", "-s", deviceId, "install", appPath};
        try {
            Process process = new ProcessBuilder(installAppCmd).redirectErrorStream(true).start();
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            while (null != (line = in.readLine())) {
                logger.debug("设备[{}]安装app[{}]打印：{}",deviceId,appPath,line);
                stringBuilder.append(line);
            }
            String result = stringBuilder.toString();
            if (result.contains("Success")) {
                return true;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    @Override
    public boolean activateApp(String deviceId, String appPackage) {
        AdbDevice currentDevice = AndroidDeviceManager.getInstance().getCurrentDevice(deviceId);
        if (null == currentDevice) {
            throw new ExecuteException("设备不在线，无法启动app");
        }
        Adb adb = AndroidDeviceManager.getInstance().getAdb();
        if (adb == null) {
            try {
                adb = new Adb();
            } catch (IOException e) {
                logger.warn("adb通信出现错误", e);
                return false;
            }
        }
        AdbTransport shell = adb.shell(currentDevice, "monkey -p " + appPackage + " -v 1");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
            String line = null;
            while (null != (line = reader.readLine())) {
                logger.debug("设备【{}】启动应用打印：{}", deviceId, line);
            }
            return true;
        } catch (IOException e) {
            logger.warn("启动app出现错误", e);
        }
        return false;
    }

    @Override
    public File getScreenShotFile(String serial) {
        return null;
    }

    @Override
    public File getScreenShotFile(String deviceId, Integer startX, Integer startY, Integer cutWidth, Integer cutHeight, Integer screenWidth, Integer screenHeight, int width, int height) {
        return null;
    }
}
