package ru.yandex.autotests.direct.web.pages.showcampbem.blocks;

import java.util.LinkedList;
import java.util.List;

import org.hamcrest.Matcher;
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.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.HtmlElement;
import ru.yandex.qatools.htmlelements.element.Link;

import static ch.lambdaj.Lambda.extract;
import static ch.lambdaj.Lambda.on;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * @author: Alex Samokhin (alex-samo@yandex-team.ru)
 * Date: 13.01.14
 */

@Name("Попап меток")
@FindBy(css = ".b-campaign-tags")
public class TagsPopupBlock extends HtmlElement {

    @Name("Метки")
    @FindBy(css = ".b-campaign-tags__tag")
    private List<WebElement> tags;

    @Name("Задать/редактировать метки")
    @FindBy(xpath = ".//a[contains(@class, 'b-campaign-tags__edit-link')]")
    private Link addOrEditTagsLink;

    @Name("Показать объявления без меток")
    @FindBy(xpath = ".//a[contains(@href, '&tag=-1')]")
    private Link showBannersWithoutTagsLink;

    public List<String> getTagTexts() {
        List<String> tagTexts = new LinkedList<>();
        tagTexts.addAll(extract(tags, on(WebElement.class).getText()));
        return tagTexts;
    }

    private WebElement getTagLink(String tagText) {
        for (WebElement tag : tags) {
            if (tag.getText().toLowerCase().startsWith(tagText.toLowerCase())) {
                return tag;
            }
        }
        return null;
    }

    public void checkTags(Matcher<Iterable<? extends String>> matcher) {
        assertThat(getTagTexts(), matcher);
    }

    public void clickOnTag(String tagText) {
        WebElement tag = getTagLink(tagText);
        if (tag == null) {
            throw new DirectWebError("не найдена метка " + tagText);
        } else {
            tag.findElement(By.cssSelector("a")).click();
        }
    }

    public void clickOnAddOrEditTagLink() {
        addOrEditTagsLink.click();
    }

    public void clickOnShowBannersWithoutTagsLink() {
        showBannersWithoutTagsLink.click();
    }
}
