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

import com.alibaba.fastjson.JSONObject;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import io.appium.java_client.ios.IOSDriver;
import net.northking.cctp.element.core.IExecuteContext;
import net.northking.cctp.element.mobile.utils.HttpUtils;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;

public class FunctionKeyUtil {

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

    private static final String HOME_PRESS = "http://%s:%s/wda/homescreen";

    private static final String PROXY_PORT_KEY = "webDriverAgentUrl";

    /**
     * <p>点击home键</p>
     * @param driver
     * @param context
     * //todo:iphone6不行
     */
    public static void pressKeyHome(AppiumDriver<WebElement> driver, IExecuteContext context) {
        if (driver instanceof AndroidDriver){
            AndroidDriver<WebElement> androidDriver=(AndroidDriver<WebElement>)driver;
            androidDriver.pressKey(new KeyEvent(AndroidKey.HOME));
        }else if (driver instanceof IOSDriver){
            String host = driver.getRemoteAddress().getHost();
            String wdaUrl = (String) driver.getCapabilities().getCapability(PROXY_PORT_KEY);
            String port = wdaUrl.substring(wdaUrl.lastIndexOf(":") + 1);
            String address = String.format(HOME_PRESS, host, port);
            URI uri = null;
            try {
                logger.debug("请求地址：{}",address);
                uri = new URI(address);
            } catch (URISyntaxException e) {
                logger.error("",e);
            }
            HttpUtils.doPost(uri, null, JSONObject.class);
        }
    }


    /**
     * <p>点击返回键，android</p>
     * @param driver
     */
    public static void pressKeyBack(AppiumDriver<WebElement> driver) {
        AndroidDriver<WebElement> androidDriver=(AndroidDriver<WebElement>)driver;
        androidDriver.pressKey(new KeyEvent(AndroidKey.BACK));
    }

    /**
     * <p>点击功能菜单键，android</p>
     * @param driver
     */
    public static void pressKeyMenu(AppiumDriver<WebElement> driver) {
        AndroidDriver<WebElement> androidDriver=(AndroidDriver<WebElement>)driver;
        androidDriver.pressKey(new KeyEvent(AndroidKey.APP_SWITCH));
    }

}
