package net.northking.cctp.element.mobile.utils.phoneUtils;

import net.northking.cctp.element.core.exception.ExecuteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.appium.java_client.AppiumDriver;
import net.northking.cctp.element.core.IExecuteContext;
import net.northking.cctp.element.mobile.constants.ConfigPath;
import net.northking.cctp.element.mobile.utils.HttpUtils;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebElement;
import org.springframework.http.HttpEntity;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : yineng.huang
 * @date : 2024/4/10 18:01
 */
public class AndroidUtil {

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

    public static void activeAndroidApp(IExecuteContext context, AppiumDriver<WebElement> driver, String appPackage) {
        String activeAppPath = context.getProperty(ConfigPath.ACTIVE_IOS_APP_ADDRESS_KEY);
        Map<String, Object> deviceInfo = context.getDeviceInfo();
        String host = driver.getRemoteAddress().getHost();  //上位机地址
        String port = (String) deviceInfo.get("port");   //上位机端口
        String url = String.format(ConfigPath.HTTP_FORMAT, host, port, activeAppPath);
        Capabilities capabilities = driver.getCapabilities();
        String deviceId = (String) capabilities.getCapability("deviceName");
        HashMap<String, Object> body = new HashMap<>();
        body.put("deviceId", deviceId);
        body.put("appPackage", appPackage);
        body.put("platform", "0");
        HttpEntity<Map> httpEntity = new HttpEntity<>(body, null);
        try {
            logger.debug("启动app的路径：{}",url);
            Boolean result = HttpUtils.doPost(url, httpEntity, Boolean.class);
            logger.info("app启动完成，响应结果：{}", result);
        } catch (Exception e) {
            throw new ExecuteException(String.format("设备【{}】app【{}】启动失败！", deviceId,appPackage));
        }
    }
}
