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

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

import ru.yandex.autotests.direct.web.util.DirectWebError;
import ru.yandex.qatools.htmlelements.element.CheckBox;

/**
 * @author Roman Kuhta (kuhtich@yandex-team.ru)
 */
public class TumblerBEM extends CheckBox {
    /**
     * Specifies wrapped {@link org.openqa.selenium.WebElement}.
     *
     * @param wrappedElement {@code WebElement} to wrap.
     */
    public TumblerBEM(WebElement wrappedElement) {
        super(wrappedElement);
    }

    private WebElement getBemElement() {
        return getWrappedElement().findElement(By.xpath("ancestor::*[contains(@class, 'tumbler_theme_normal')][1]"));
    }

    private WebElement getButton() {
        return getBemElement().findElement(By.xpath(".//*[contains(@class,'tumbler__button')]"));
    }

    @Override
    public void select() {
        if (!isSelected()) {
            try {
                getButton().click();
                Thread.sleep(2000);
            }
            catch (Exception e) {
                throw new DirectWebError("ошибка при переключении тумблера");
            }
        }
    }

    @Override
    public void deselect() {
        if (isSelected()) {
            getButton().click();
        }
    }

    @Override
    public boolean isSelected() {
        return Boolean.valueOf(getWrappedElement().getAttribute("value"));
    }
}
