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 UsersContentComponent extends BaseMobileComponent {
    private final ElementsCollection items = allByIdInRoot("user_item");

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

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

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

    public UserItemComponent byUsername(String username) {
        items.shouldHave(CollectionCondition.sizeGreaterThan(0), Duration.ofSeconds(15));
        for (int i = 0; i < items.size(); i++) {
            UserItemComponent item = get(i);
            if (username.equals(item.usernameText())) {
                return item;
            }
        }
        throw new IllegalStateException("User with username '" + username + "' was not found.");
    }
}
