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

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import net.northking.cctp.element.core.DeviceDriver;
import net.northking.cctp.element.core.exception.ExecuteException;
import net.northking.cctp.element.mobile.utils.CommonUtils;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;

public class InputFromKeyBoardThread implements Callable<Boolean> {

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

    private DeviceDriver deviceDriver;
    private Float preExecuteWait;
    private Float sufExecuteWait;
    private Integer keyCode;

    public InputFromKeyBoardThread(DeviceDriver deviceDriver,Integer keyCode,Float preExecuteWait,Float sufExecuteWait){
        this.deviceDriver = deviceDriver;
        this.preExecuteWait = preExecuteWait;
        this.sufExecuteWait = sufExecuteWait;
        this.keyCode = keyCode;
    }


    @Override
    public Boolean call() throws Exception {
        CommonUtils.handlePreExecuteWait(preExecuteWait);
        if (deviceDriver instanceof AndroidDriver) {
            AndroidDriver<WebElement> androidDriver = (AndroidDriver<WebElement>) deviceDriver;
            if (this.keyCode == AndroidKey.ENTER.getCode()) {
                logger.info("输入回车。。。。。。。,{}",this.keyCode);
                androidDriver.pressKey(new KeyEvent(AndroidKey.ENTER));
            } else if (this.keyCode == AndroidKey.ESCAPE.getCode()) {
                logger.info("输入返回。。。。。。。,{}",this.keyCode);
                androidDriver.pressKey(new KeyEvent(AndroidKey.ESCAPE));
            } else if (this.keyCode == AndroidKey.TAB.getCode()) {
                logger.info("输入TAB。。。。。。。,{}",this.keyCode);
                androidDriver.pressKey(new KeyEvent(AndroidKey.TAB));
            } else {
                logger.warn("该操作目前暂时只有回车、返回、TAB");
                return false;
            }
        } else {
            throw new ExecuteException("该操作只支持Android设备");
        }
        CommonUtils.handleSufExecuteWait(sufExecuteWait);
        return true;
    }
}
