package ru.otus.mobile.screens;

import com.codeborne.selenide.ElementsCollection;
import com.codeborne.selenide.SelenideElement;
import io.appium.java_client.AppiumBy;
import org.openqa.selenium.WebElement;
import ru.otus.mobile.ui.MobileUi;

public class GiftsScreen {

    public void open() {
        if (MobileUi.existsById("gifts_content")) {
            return;
        }
        if (MobileUi.existsById("gift_item")
                || MobileUi.existsById("list_item")) {
            return;
        }
        MobileUi.byIdOrAccessibility("gifts_content");
    }

    public void createGift(String name) {
        if (!MobileUi.existsById("add_button")) {
            open();
        }
        MobileUi.byIdOrAccessibility("add_button").click();
        typeInto("name_input", name);
        typeInto("price_input", "100");
        MobileUi.byIdOrAccessibility("save_button").click();
    }

    public void editGift(String oldName, String newName) {
        openGift(oldName);
        if (MobileUi.existsById("edit_button")) {
            MobileUi.byIdOrAccessibility("edit_button").click();
        }
        typeInto("name_input", newName);
        MobileUi.byIdOrAccessibility("save_button").click();
    }

    public void assertGiftPresent(String name) {
        scrollToGiftName(name);
    }

    private void openGift(String name) {
        SelenideElement byText = MobileUi.byTextContains(name);
        if (byText.exists()) {
            byText.click();
            return;
        }
        scrollToGiftName(name).click();
        if (MobileUi.existsById("edit_button")
                || MobileUi.existsById("gift_edit_bottom_sheet")) {
            return;
        }
        ElementsCollection items = MobileUi.allById("gift_item");
        if (items.isEmpty()) {
            items = MobileUi.allById("list_item");
        }
        items.first().click();
    }

    private SelenideElement scrollToGiftName(String name) {
        String safe = name.replace("\"", "\\\"");
        String selector = "new UiScrollable(new UiSelector().scrollable(true))"
                + ".scrollIntoView(new UiSelector().textContains(\"" + safe + "\"))";
        return com.codeborne.selenide.Selenide.$(AppiumBy.androidUIAutomator(selector));
    }

    private void typeInto(String id, String value) {
        WebElement input = MobileUi.byIdOrAccessibility(id)
                .toWebElement();
        input.click();
        input.clear();
        input.sendKeys(value);
    }
}
