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

import java.util.List;

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

/**
 * Created by aleran on 20.08.2015.
 */
public class HierarchicalMultipliersRadioBEM extends RadioBEM {
    /**
     * Specifies a radio button of a radio button group that will be used to find all other buttons of this group.
     *
     * @param wrappedElement {@code WebElement} representing radio button.
     */
    public HierarchicalMultipliersRadioBEM(WebElement wrappedElement) {
        super(wrappedElement);
    }


    public WebElement getParentElement() {
        return super.getWrappedElement().findElement(By.xpath("./ancestor::span[contains(@class, 'radio-button')][1]"));
    }

    @Override
    public void selectByValue(String value) {
        selectButton(getButton(value));
    }

    @Override
    public List<WebElement> getButtons() {
        String radioName = super.getWrappedElement().getAttribute("name");

        String xpath;
        if (radioName == null) {
            xpath = ".//input[@type = 'radio']";
        } else {
            xpath = String.format(
                    ".//input[@type = 'radio' and @name = '%s']",
                    radioName
            );
        }

        return getParentElement().findElements(By.xpath(xpath));
    }

    @Override
    public WebElement getSelectedButton() {
        for (WebElement button : getButtons()) {
            if (button.isSelected() || button.findElement(By.xpath("parent::*")).getAttribute("class").
                    contains("radio-button__radio_pressed_yes")||button.findElement(By.xpath("parent::*")).getAttribute("class").
                    contains("radio-button__radio_checked_yes")) {
                return button;
            }
        }

        throw new NoSuchElementException("No selected button");
    }

    //Возвращает кнопку с соответствующим значением value и которой соответствует видимый родительский span
    private WebElement getButton(String value) {
        for (WebElement button : getButtons()) {
            String buttonValue = button.getAttribute("value");
            if (value.equals(buttonValue) && button.findElement(By.xpath("parent::*")).isDisplayed()) {
                return button;
            }
        }
        throw new NoSuchElementException(String.format("Cannot locate radio button with value: %s", value));
    }

    private void selectButton(WebElement button) {
        if (!button.isSelected()) {
            button.findElement(By.xpath("parent::*")).click();
        }
    }
}
