package ru.otus.mobile.component;

import com.codeborne.selenide.CollectionCondition;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.ElementsCollection;
import com.codeborne.selenide.SelenideElement;

import java.time.Duration;

public final class GiftsContentComponent extends BaseMobileComponent {
    private final ElementsCollection items = allByIdInRoot("gift_item");

    public GiftsContentComponent(SelenideElement root) {
        super(root);
    }

    public GiftItemComponent get(int index) {
        return new GiftItemComponent(items.get(index).shouldBe(Condition.visible, Duration.ofSeconds(15)));
    }

    public GiftItemComponent first() {
        return get(0);
    }

    public GiftItemComponent byTitle(String title) {
        items.shouldHave(CollectionCondition.sizeGreaterThan(0), Duration.ofSeconds(15));
        for (int i = 0; i < items.size(); i++) {
            GiftItemComponent item = get(i);
            if (title.equals(item.titleText())) {
                return item;
            }
        }
        throw new IllegalStateException("Gift with title '" + title + "' was not found.");
    }
}
