package org.getopentest.appium;

import io.appium.java_client.MobileDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import io.appium.java_client.touch.LongPressOptions;
import io.appium.java_client.touch.offset.ElementOption;
import java.time.Duration;
import org.getopentest.annotations.TestActionArgument;
import org.getopentest.annotations.TestActionClass;
import org.getopentest.annotations.Type;
import org.getopentest.appium.core.SwipingAction;
import org.openqa.selenium.By;

@TestActionClass(
        description = "Performs a long press gesture at the center of a UI "
        + "element for the specified duration.")
@TestActionArgument(name = "locator", type = Type.MAP, optional = false,
        description = "The locator of the UI element.")
@TestActionArgument(name = "durationMs", type = Type.INTEGER, optional = true,
        description = "The duration of the long press, in milliseconds. If the "
        + "durationMs argument is not specified, the long press will be held"
        + "until the contextmenu event has fired.")

/**
 * Performs a long press gesture at the center of a UI element.
 */
public class LongPress extends SwipingAction {

    @Override
    public void run() {
        super.run();

        By locator = this.readLocatorArgument("locator");
        Integer durationMs = this.readIntArgument("durationMs", null);

        this.swipeAndCheckElementVisible(locator, this.getSwipeOptions());

        MobileElement element = this.getElement(locator);
        TouchAction action = new TouchAction((MobileDriver) driver);

        if (durationMs == null) {
            action.longPress(LongPressOptions.longPressOptions()
                    .withElement(ElementOption.element(element)));
        } else {
            action.longPress(LongPressOptions.longPressOptions()
                    .withElement(ElementOption.element(element))
                    .withDuration(Duration.ofMillis(durationMs)));
        }

        action.release().perform();
    }
}
