package ru.otus.mobile.page;

import com.codeborne.selenide.Condition;
import com.google.inject.Inject;
import ru.otus.mobile.component.BottomNavigationComponent;
import ru.otus.mobile.component.WishlistFormComponent;
import ru.otus.mobile.config.MobileConfig;

public final class WishlistsPage extends AbsBasePage {
    private final WishlistFormComponent form;

    @Inject
    public WishlistsPage(MobileConfig config, BottomNavigationComponent bottomNavigation, WishlistFormComponent form) {
        super(config, bottomNavigation);
        this.form = form;
    }

    public void open() {
        bottomNavigation.openWishlists();
        byId("wishlists_content").shouldBe(Condition.visible);
    }

    public void createWishlist(String name) {
        tap("add_button");
        form.save(name);
    }

    public void editWishlist(String oldName, String newName) {
        ensureWishlistsList();
        editButtonFor(oldName).shouldBe(Condition.visible).click();
        form.save(newName);
    }

    public void shouldSeeWishlist(String name) {
        scrollToText(name).shouldBe(Condition.visible);
    }

    public void openWishlist(String name) {
        scrollToText(name).click();
    }

    private void ensureWishlistsList() {
        if (exists("wishlist_item") || exists("wishlists")) {
            return;
        }
        if (exists("gifts_content") || exists("gift_item") || exists("add_button")) {
            back();
        }
        byId("wishlists_content").shouldBe(Condition.visible);
    }

    private com.codeborne.selenide.SelenideElement editButtonFor(String name) {
        String full = config().appPackage();
        String xpath = "//androidx.recyclerview.widget.RecyclerView[@resource-id='" + full + ":id/wishlists']"
                + "//android.view.ViewGroup[@resource-id='" + full + ":id/wishlist_item'"
                + " and .//android.widget.TextView[@resource-id='" + full + ":id/title'"
                + " and contains(@text," + xpathLiteral(name) + ")]]"
                + "//android.widget.Button[@resource-id='" + full + ":id/edit_button']";
        return byXpath(xpath);
    }
}
