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

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.support.FindBy;

import ru.yandex.autotests.direct.web.pages.campaigns.blocks.EditTagRow;
import ru.yandex.autotests.direct.web.util.DirectWebError;
import ru.yandex.qatools.allure.webdriver.pages.BasePageObject;
import ru.yandex.qatools.allure.webdriver.steps.WebDriverSteps;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.Button;
import ru.yandex.qatools.htmlelements.element.TextInput;

import static ru.yandex.autotests.direct.web.util.WebElementsActions.fillTextInput;

/**
 * @author: Alex Samokhin (alex-samo@yandex-team.ru)
 * Date: 13.01.14
 */
public class EditCampaignTagsPage extends BasePageObject {

    List<EditTagRow> tagRows;

    @Name("Новые метки")
    @FindBy(xpath = ".//input[@name='new_tags']")
    private TextInput newTagsTextInput;

    @Name("Сохранить")
    @FindBy(xpath = ".//button[@type='submit']")
    private Button saveButton;

    private EditTagRow getTagRow(String tag) {
        for (EditTagRow tagRow : tagRows) {
            if (tagRow.getTagText().equalsIgnoreCase(tag)) {
                return tagRow;
            }
        }
        return null;
    }

    public void editTag(String oldTag, String newTag) {
        EditTagRow tagRow = getTagRow(oldTag);
        if (tagRow == null) {
            throw new DirectWebError("не найдена строка редактирования метки " + oldTag);
        } else {
            tagRow.fillTagTextInput(newTag);
            saveButton.click();
        }
    }

    public void deleteTag(String tag) {
        EditTagRow tagRow = getTagRow(tag);
        if (tagRow == null) {
            throw new DirectWebError("не найдена строка редактирования метки " + tag);
        } else {
            tagRow.clickOnDeleteTag();
            saveButton.click();
        }
    }

    public void saveNewTags(String... tags) {
        fillTextInput(newTagsTextInput, StringUtils.join(tags, ","));
        WebDriverSteps.getInstance(WebDriverSteps.class, config).takeScreenshot();
        saveButton.click();
    }

}
