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

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.ios.IOSDriver;
import net.northking.cctp.element.core.IExecuteContext;
import net.northking.cctp.element.core.exception.ExecuteException;
import net.northking.cctp.element.mobile.constants.ConfigPath;
import net.northking.cctp.element.mobile.entity.PointMessage;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.util.StringUtils;

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

public class CommonUtils {

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

    public static void handleSufExecuteWait(Float sufExecuteWait) {
        if (sufExecuteWait > 0) {
            long waitTime = sufExecuteWait.longValue() * 1000;
            try {
                Thread.sleep(waitTime);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
    }

    public static void handlePreExecuteWait(Float preExecuteWait) {
        if (preExecuteWait > 0) {
            long waitTime = preExecuteWait.longValue() * 1000;
            try {
                Thread.sleep(waitTime);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
    }

    public static String handleVariable(IExecuteContext context, String text) {
        if (StringUtils.hasText(text) && (RegexUtils.containScriptVar(text) || RegexUtils.containGlobalVar(text))) {  //脚本变量
            String value = context.getVariable(text);
            logger.debug("传入text:{},使用变量：{}去拿结果，拿到的结果：{}", text, text, value);
            if (null == value) {
                throw new ExecuteException(String.format("变量【%s】不存在！", value));
            }
            return value;
        }
        return text;
    }

    public static void screenShot(IExecuteContext context, AppiumDriver<WebElement> driver) {
        screenShot(context, driver, null);
    }

    public static void screenShot(IExecuteContext context, AppiumDriver<WebElement> driver, PointMessage point) {
        String screenShotAddress = context.getProperty(ConfigPath.UPLOAD_MOBILE_SCREEN_SHOT_ADDRESS_KEY); //截全屏地址
        Map<String, Object> deviceInfo = context.getDeviceInfo();
        String host = driver.getRemoteAddress().getHost(); //上位机地址
        String port = (String) deviceInfo.get("port");
        String resolution = (String) deviceInfo.get("resolution");
        String shotAllScreenAddress = String.format(ConfigPath.HTTP_FORMAT, host, port, screenShotAddress);
        String deviceId = (String) driver.getCapabilities().getCapability("deviceName");
        Map<String, String> screenParam = new HashMap<>();
        screenParam.put("deviceId", deviceId);
        String tenantId = (String) context.getContextVariable("__tenantId");
        logger.debug("tenantId：{}",tenantId);
        screenParam.put("tenantId",tenantId);
        screenParam.put("resolution",resolution);
        if (driver instanceof AndroidDriver) {
            screenParam.put("platform","0");
        }else if(driver instanceof IOSDriver) {
            screenParam.put("platform","1");
        }
        if (null != point) {
            screenParam.put("x", String.valueOf(point.getX()));
            screenParam.put("y", String.valueOf(point.getY()));
        }
        HttpEntity<Map> screenEntity = new HttpEntity<>(screenParam, null);
        String picAddress = HttpUtils.doPost(shotAllScreenAddress, screenEntity, String.class, 20 * 1000);
        logger.debug("截图地址：{}", picAddress);
        if (!StringUtils.hasText(picAddress)) {
            logger.warn("设备【{}】截图失败", deviceId);
        }
        context.setVariable("mobileStepSnapshot",picAddress);
    }
}
