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

import io.appium.java_client.AppiumDriver;
import net.northking.cctp.element.core.DeviceDriver;
import net.northking.cctp.element.core.IExecuteContext;
import net.northking.cctp.element.core.IStepTarget;
import net.northking.cctp.element.core.exception.ExecuteException;
import net.northking.cctp.element.mobile.entity.PointMessage;
import net.northking.cctp.element.mobile.utils.CommonUtils;
import net.northking.cctp.element.mobile.utils.phoneUtils.ElementUtil;
import net.northking.cctp.element.mobile.utils.phoneUtils.HandleUtils;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.Callable;

public class LongPressThread implements Callable<Boolean> {

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

    private IExecuteContext context;
    private DeviceDriver deviceDriver;
    private List<IStepTarget> targets;
    private Integer waitTimeout;
    private String waitStatusStr;
    private String swipe;
    private Integer swipeCount;
    private Float preExecuteWait;
    private Float sufExecuteWait;

    public LongPressThread(IExecuteContext context, DeviceDriver deviceDriver, List<IStepTarget> targets, Integer waitTimeout, String waitStatusStr, String swipe, Integer swipeCount, Float preExecuteWait, Float sufExecuteWait) {
        this.context = context;
        this.deviceDriver = deviceDriver;
        this.targets = targets;
        this.waitTimeout = waitTimeout;
        this.waitStatusStr = waitStatusStr;
        this.swipe = swipe;
        this.swipeCount = swipeCount;
        this.preExecuteWait = preExecuteWait;
        this.sufExecuteWait = sufExecuteWait;
    }

    @Override
    public Boolean call() throws Exception {
        CommonUtils.handlePreExecuteWait(preExecuteWait);
        boolean waitStatus = "1".equals(waitStatusStr);
        AppiumDriver<WebElement> driver = (AppiumDriver<WebElement>) deviceDriver;
        PointMessage point = ElementUtil.findWebElement(context, driver, targets, waitTimeout, waitStatus, swipe, swipeCount);
        if (point == null) {
            logger.error("查找不到控件");
            throw new ExecuteException("查找不到控件");
        }
        ElementUtil.pointGetRedDot(point, context, driver);
        try {
            HandleUtils.longPress(context,driver, point);
        } catch (Exception e) {
            logger.error("长按元素失败：{}", e);
            throw new ExecuteException("长按控件失败");
        }
        CommonUtils.handleSufExecuteWait(sufExecuteWait);
        return true;
    }
}
