package ru.yandex.autotests.direct.web.webelements.bem;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import ru.yandex.autotests.direct.web.util.DirectWebError;
import ru.yandex.autotests.direct.web.util.StringHelper;
import ru.yandex.qatools.htmlelements.element.Select;
import ru.yandex.qatools.htmlelements.matchers.WebElementMatchers;

import static ru.yandex.autotests.direct.utils.matchers.BeanEqualsAssert.assertThat;
import static ru.yandex.autotests.direct.web.util.OperationSystemUtils.sleep;
import static ru.yandex.qatools.htmlelements.matchers.MatcherDecorators.should;
import static ru.yandex.qatools.htmlelements.matchers.decorators.TimeoutWaiter.timeoutHasExpired;

public class RetargetingSelectBem extends Select {

    private static final String POPUP_XPATH = "//div[contains(@class, 'b-retargeting-condition-edit-rule__list-popup')"
            + " and contains(@class, 'visibility_visible')]";

    public RetargetingSelectBem(WebElement wrappedElement) {
        super(wrappedElement);
    }

    public void openSelect() {
        if (!isOpen()) {
            //Кнопка не всегад срабатывает с первого клика, поэтому сначала sendKeys для фокуса
            getWrappedElement().sendKeys("");
            getWrappedElement().click();
            sleep(500);
            assertThat(getPopup(), should(WebElementMatchers.isDisplayed()).whileWaitingUntil(timeoutHasExpired(5000)));
        }
    }

    @Override
    public void selectByVisibleText(String text) {
        openSelect();
        getOptions().stream()
                .filter(x -> StringHelper.equalsIgnoreDiffWhitespaces(x.getText(), text))
                .findFirst()
                .orElseThrow(() -> new DirectWebError("Не найдено значение: " + text))
                .click();
    }

    @Override
    public void selectByValue(String value) {
        throw new UnsupportedOperationException();
    }

    private WebElement getPopup() {
        return getWrappedElement().findElement(By.xpath(POPUP_XPATH));
    }

    private boolean isOpen() {
        return getWrappedElement().getAttribute("aria-expanded").contains("true");
    }

    @Override
    public List<WebElement> getOptions() {
        return getPopup().findElements(By.xpath(".//div[contains(@class, 'list-popup-content-item')]"));
    }

    @Override
    public WebElement getFirstSelectedOption() {
        return getWrappedElement().findElement(By.xpath("./span"));
    }
}
