package ru.yandex.autotests.direct.web.pages.regionselectpopup;

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

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

import ru.yandex.autotests.direct.web.util.DirectWebError;
import ru.yandex.autotests.direct.web.util.StringHelper;
import ru.yandex.autotests.direct.web.webelements.bem.CheckBoxBEM;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.HtmlElement;

import static com.google.common.collect.Iterables.getLast;

public class RegionLineBlockBEM extends HtmlElement {

    @Name("Чекбоксы регионов")
    @FindBy(xpath = ".//span[contains(@class, 'b-regions-tree__region-checkbox')]//input")
    private CheckBoxBEM checkBox;

    @Name("Кнопки раскрытия подрегионов")
    @FindBy(xpath = ".//div[@class = 'b-regions-tree__expand']")
    private WebElement expandButton;

    @Name("Названия регионов")
    @FindBy(xpath = ".//label[contains(@class, 'b-regions-tree__region-name')]")
    private WebElement label;

    public void expand() {
        if (!isExpanded()) {
            expandButton.click();
        }
    }

    @Name("Кнопки открытия попапа корректировок")
    @FindBy(xpath = ".//span[contains(@class, 'b-regions-tree__edit-bid')]")
    private WebElement geoBidCorrection;

    public void openBidCorrection() {
        geoBidCorrection.click();
    }

    public String getRegionID() {
        return getLast(StringHelper.getNumericDataFromText(findElement(By.xpath(".//input")).getAttribute("id")))
                .toString();
    }

    public void select() {
        checkBox.select();
    }

    public void deselect() {
        checkBox.deselect();
    }

    public String getParentRegion() {
        Matcher m = Pattern.compile("b-regions-tree__inner_parent-id_\\d*").matcher(getWrappedElement().
                findElement(By.xpath(
                        "//div[div/div[contains(@class, 'b-regions-tree__region_id_" + getRegionID() + " ')]]")).
                getAttribute("class"));
        if (m.find()) {
            return m.group().replace("b-regions-tree__inner_parent-id_", "");
        } else {
            return "";
        }
    }

    public boolean isExpanded() {
        String classString = getWrappedElement().getAttribute("class");
        if (classString.contains("b-regions-tree__region_expanded_no")) {
            return false;
        } else if (classString.contains("b-regions-tree__region_expanded_yes")) {
            return true;
        } else {
            throw new DirectWebError("Не удалось найти атрибут b-regions-tree__region_expanded в классе элемента");
        }
    }

    public boolean isSelected() {
        return checkBox.isSelected();
    }
}
