package ru.otus.mobile.page;

import com.codeborne.selenide.Condition;
import com.google.inject.Singleton;
import ru.otus.mobile.component.GiftItemComponent;
import ru.otus.mobile.component.GiftsContentComponent;
import ru.otus.mobile.component.UsersContentComponent;
import ru.otus.mobile.component.UsersFilterComponent;
import ru.otus.mobile.component.WishlistsContentComponent;

import java.time.Duration;

@Singleton
public final class UsersPage extends AbsBasePage {
    private final UsersContentComponent usersContent = new UsersContentComponent(byId("users_content"));
    private final UsersFilterComponent usersFilter = new UsersFilterComponent(byId("users_filter_bottom_sheet"));
    private final WishlistsContentComponent wishlistsContent = new WishlistsContentComponent(byId("wishlists_content"));
    private final GiftsContentComponent giftsContent = new GiftsContentComponent(byId("gifts_content"));
    private GiftItemComponent currentGift;

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

    public void filterByUsername(String username) {
        topBar.openUsersFilter();
        usersFilter.shouldBe(Condition.visible, Duration.ofSeconds(15));
        usersFilter.applyByUsername(username);
        usersContent.byUsername(username);
    }

    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() {
        currentGift = giftsContent.get(0);
    }

    public void openGift(String name) {
        currentGift = giftsContent.byTitle(name);
    }

    public boolean isReserved() {
        return selectedGift().isReserved();
    }

    public void toggleReservation() {
        selectedGift().toggleReservation();
    }

    private GiftItemComponent selectedGift() {
        if (currentGift == null) {
            throw new IllegalStateException("Gift is not selected. Call openFirstGift/openGift first.");
        }
        return currentGift;
    }
}
