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.WishlistsContentComponent;
import ru.otus.mobile.component.WishlistFormComponent;

public final class WishlistsPage extends AbsBasePage {
    private final WishlistFormComponent form;
    private final com.codeborne.selenide.SelenideElement addButton = byId("add_button");

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

    public void open() {
        bottomNavigation.openWishlists();
        contentRoot().shouldBe(Condition.visible);
    }

    public void createWishlist(String name) {
        addButton.click();
        form.save(name);
    }

    public void editWishlist(String oldName, String newName) {
        ensureWishlistsList();
        content().byTitle(oldName).edit();
        form.save(newName);
    }

    public void shouldSeeWishlist(String name) {
        content().byTitle(name).shouldHaveTitle(name);
    }

    public void openWishlist(String name) {
        content().byTitle(name).open();
    }

    public void openFirstWishlist() {
        content().first().open();
    }

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

    private WishlistsContentComponent content() {
        return new WishlistsContentComponent(contentRoot());
    }

    private com.codeborne.selenide.SelenideElement contentRoot() {
        if (byId("wishlists_content").exists()) {
            return byId("wishlists_content");
        }
        return byId("wishlists");
    }
}
