package ru.otus.mobile.page;

import com.codeborne.selenide.Condition;
import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.WebDriverRunner;
import com.codeborne.selenide.appium.SelenideAppiumCollection;
import io.appium.java_client.AppiumBy;

import static com.codeborne.selenide.appium.SelenideAppium.$$;
import static com.codeborne.selenide.appium.SelenideAppium.$;

public abstract class AbsPageObject {
    private static final String APP_PACKAGE_PROPERTY = "app.package";
    private static final String DEFAULT_APP_PACKAGE = "ru.otus.wishlist";

    protected SelenideElement byId(String id) {
        return $(AppiumBy.id(fullIdValue(id)));
    }

    protected SelenideAppiumCollection allById(String id) {
        return $$(AppiumBy.id(fullIdValue(id)));
    }

    protected void type(String id, String value) {
        SelenideElement input = byId(id).shouldBe(Condition.visible);
        input.click();
        input.clear();
        input.sendKeys(value);
    }

    protected void tap(String id) {
        byId(id).shouldBe(Condition.visible).click();
    }

    protected boolean exists(String id) {
        return byId(id).exists();
    }

    protected void back() {
        WebDriverRunner.getWebDriver().navigate().back();
    }

    protected static String fullIdValue(String id) {
        if (id.contains(":")) {
            return id;
        }
        String appPackage = System.getProperty(APP_PACKAGE_PROPERTY, DEFAULT_APP_PACKAGE);
        return appPackage + ":id/" + id;
    }
}
