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

import io.appium.java_client.AppiumDriver;
import net.northking.cctp.element.mobile.utils.phoneUtils.ScreenUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

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

public class Xpath implements Callable<WebElement> {

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

    private AppiumDriver<WebElement> driver;

    private String xpath;

    private boolean more = true;

    private int address = 1;

    private String swipe = "0";

    private int swipeCount = 0;

    private boolean running = true;

    private int timeout = 30;


    public static Xpath build(AppiumDriver<WebElement> driver, String xpath) {
        return new Xpath().setDriver(driver).setXpath(xpath);
    }

    private Xpath setDriver(AppiumDriver<WebElement> driver) {
        this.driver = driver;
        return this;
    }

    private Xpath setXpath(String xpath) {
        this.xpath = xpath;
        return this;
    }

    public Xpath isSwipe(String swipe) {
        this.swipe = swipe;
        return this;
    }

    public Xpath setSwipeCount(Integer swipeCount) {
        this.swipeCount = swipeCount;
        return this;
    }

    public Xpath isMore(boolean more) {
        this.more = more;
        return this;
    }

    public Xpath setAddress(Integer address){
        this.address = address;
        return this;
    }

    public Xpath withTimeout(Integer timeout){
        this.timeout = timeout;
        return this;
    }

    public void kill() {
        this.running = false;
    }

    @Override
    public WebElement call() throws Exception {
        Integer perPageTimeout = timeout;
        Integer swipeNum = swipeCount;
        if ((swipeCount <= 0 && swipeCount > 5)/*限定滑屏查找不超过5次*/ || "0".equals(swipe)  /*不滑屏*/) {
            swipeNum = 0;
        }
        if (swipeNum > 0) {
            perPageTimeout = timeout / swipeCount;
        }
        this.driver.manage().timeouts().implicitlyWait(perPageTimeout, TimeUnit.SECONDS);
        while (running && swipeNum >= 0) {
            List<WebElement> elements = driver.findElements(By.xpath(xpath));
            logger.info("找到元素{}个",elements.size());
            if (!CollectionUtils.isEmpty(elements)) {   //xpath找到了
                if (elements.size() == 1) {
                    return elements.get(0);
                } else {
                    if (more && address-1<=elements.size()) {
                        return elements.get(address - 1);
                    }
                }
            } else {  //xpath没找到
                if (swipeNum > 0) {
                    ScreenUtil.standardSwipe(swipe, 2000, driver);
                }
            }
            swipeNum--;
        }
        return null;
    }
}
