package ru.yandex.autotests.direct.web.pages.campaigns.timetarget.elements;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

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 Switcher extends CheckBox {
    /**
     * Specifies wrapped {@link org.openqa.selenium.WebElement}.
     *
     * @param wrappedElement {@code WebElement} to wrap.
     */
    public Switcher(WebElement wrappedElement) {
        super(wrappedElement);
    }

    @Override
    public String getLabelText() {
        WebElement label = getLabel();
        if (label == null)
            return null;
        WebElement elem = label.findElement(By.xpath("./span"));
        if (elem == null)
            return null;
        return elem.getText();
    }

    @Override
    public WebElement getLabel() {
        return getWrappedElement().findElement(By.xpath(".//label[contains(@class, 'label_active_yes')]"));
    }

    @Override
    public void select() {
        if (!isSelected()) {
            getSwitchButton().click();
        }
    }

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

    @Override
    public boolean isSelected() {
        Pattern pattern = Pattern.compile("body_position_(left|right)");
        Matcher matcher = pattern.matcher(getWrappedElement().getAttribute("class"));
        if (matcher.find()) {
            return matcher.group().contains("left");
        } else {
            throw new DirectWebError("Cannot find switch__body_position parameter" +
                    " of class attribute");
        }
    }

    public WebElement getSwitchButton() {
        return getWrappedElement().findElement(By.xpath(".//span[@class='b-form-switch__button']"));
    }

}
