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

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import ru.yandex.autotests.direct.web.objects.adjustment.rates.InventoryMultiplierWeb;
import ru.yandex.autotests.direct.web.util.DirectWebError;
import ru.yandex.autotests.direct.web.webelements.bem.SelectBEM;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.Button;
import ru.yandex.qatools.htmlelements.element.HtmlElement;
import ru.yandex.qatools.htmlelements.element.TextInput;

import java.util.List;

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

@Name("Корректировки ставок по инвентарю")
@FindBy(css = ".b-adjustment-rates_type_cpm-group-type")
public class InvetoryMultiplierBlock extends HtmlElement {

    @Name("Добавить корректировку")
    @FindBy(css = ".b-adjustment-rates__add-rate")
    private Button addAdjustmentRates;

    @Name("Список условий")
    @FindBy(xpath = "//div[contains(@class, 'popup2')][contains(@class, 'b-rates-chooser')]" +
            "//div[contains(@class, 'menu__item')]")
    private List<WebElement> inventoryList;

    @Name("Добавить условие")
    @FindBy(xpath = "//div[contains(@class, 'popup2')][contains(@class, 'b-rates-chooser')]" +
            "//button[contains(@class, 'b-rates-chooser__add-button')]")
    private WebElement addInventory;

    @Name("Направление")
    @FindBy(css = ".b-adjustment-rates__control_type_sign select")
    private SelectBEM inventoryPctTypeSelect;

    @Name("Тип инвентаря")
    @FindBy(xpath = "//button[contains(@class, 'b-adjustment-rates__button')]//div")
    private WebElement inventoryName;

    @Name("Умножать на")
    @FindBy(xpath = "(.//span[contains(@class, 'b-adjustment-rates__input')]//input)[2]")
    private TextInput inventoryPctTextInput;

    public InventoryMultiplierWeb getInventoryMultiplier(){
        return new InventoryMultiplierWeb()
                .withMultiplierPct(inventoryPctTextInput.getText())
                .withMultiplierName(inventoryName.getText());
    }

    public void selectInventoryByText(String name) {
        inventoryList
                .stream()
                .filter(x -> x.getText().equals(name))
                .findFirst()
                .orElseThrow(() -> new DirectWebError("Не найдено значение в селекте, удовлетворяющее условию"))
                .findElement(By.xpath(".//input"))
                .click();
    }

    public void fillInventoryMultiplier(InventoryMultiplierWeb inventoryMultiplier){
        addInventory(inventoryMultiplier);
        fillTextInput(inventoryPctTextInput, inventoryMultiplier.getMultiplierPct());
    }

    public void addInventory(InventoryMultiplierWeb inventoryMultiplier) {
        addAdjustmentRates.click();
        selectInventoryByText(inventoryMultiplier.getInventoryName());
        addInventory.click();
    }
}
