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.GiftsContentComponent;
import ru.otus.mobile.component.TopBarComponent;
import ru.otus.mobile.component.UsersContentComponent;
import ru.otus.mobile.component.UsersFilterComponent;
import ru.otus.mobile.component.WishlistsContentComponent;

import java.time.Duration;

public final class UsersPage extends AbsBasePage {
    private final TopBarComponent topBar;

    @Inject
    public UsersPage(BottomNavigationComponent bottomNavigation) {
        super(bottomNavigation);
        this.topBar = new TopBarComponent(byId("android:id/content"));
    }

    public void open() {
        bottomNavigation.openUsers();
        usersContentRoot().shouldBe(Condition.visible, Duration.ofSeconds(15));
    }

    public void filterByUsername(String username) {
        topBar.openUsersFilter();
        byId("users_filter_bottom_sheet").shouldBe(Condition.visible, Duration.ofSeconds(15));
        new UsersFilterComponent(byId("users_filter_bottom_sheet")).applyByUsername(username);
        byId("user_item").shouldBe(Condition.visible, Duration.ofSeconds(15));
    }

    public void openUser(String username) {
        usersContent().byUsername(username).open();
    }

    public void openFirstWishlist() {
        wishlistsContent().get(0).open();
    }

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

    public void openFirstGift() {
        new GiftsContentComponent(byId("gifts_content")).get(0).open();
    }

    public void openGift(String name) {
        new GiftsContentComponent(byId("gifts_content")).byTitle(name).open();
    }

    public boolean isReserved() {
        return Boolean.parseBoolean(byId("reserved").shouldBe(Condition.visible).getAttribute("checked"));
    }

    public void toggleReservation() {
        byId("reserved").shouldBe(Condition.visible).click();
    }

    private UsersContentComponent usersContent() {
        return new UsersContentComponent(usersContentRoot());
    }

    private WishlistsContentComponent wishlistsContent() {
        return new WishlistsContentComponent(wishlistsContentRoot());
    }

    private com.codeborne.selenide.SelenideElement usersContentRoot() {
        if (byId("users_content").exists()) {
            return byId("users_content");
        }
        return byId("users");
    }

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

}
