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

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

import java.util.List;

import org.hamcrest.Matcher;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import ru.yandex.autotests.direct.web.webelements.bem.FileInputBEM;
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.matchers.WebElementMatchers;

import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static ru.yandex.autotests.direct.web.util.DirectWaiters.coreWaiter;

@FindBy(css = ".p-xls-management__import-xls")
public class UploadFileBlock extends HtmlElement {

    private static final Integer TROBBER_TIMEOUT = 15;

    @Name("Поле ввода файла для загрузки")
    @FindBy(xpath = ".//input[@type='file']")
    private FileInputBEM uploadExcelFileInput;

    @Name("Продолжить")
    @FindBy(xpath = ".//button[@type = 'submit']")
    private Button continueButton;

    @Name("Индикатор загрузки")
    @FindBy(xpath = ".//div[contains(@class, 'spin')]")
    private WebElement trobber;

    @Name("Ошибки при загрузке")
    @FindBy(css = "li.b-file-preloader__error-message")
    private List<WebElement> uploadErrors;

    public void waitWhileTrobberIsDisappeared() {
        Matcher matcher = WebElementMatchers.hasAttribute("class", containsString("spin_progress_yes"));
        coreWaiter(matcher, TROBBER_TIMEOUT).matches(trobber);
        assertThat(trobber, coreWaiter(not(matcher), TROBBER_TIMEOUT));
    }

    public void uploadFile(String fileName) {
        uploadExcelFileInput.setFileToUpload(fileName);
        waitWhileTrobberIsDisappeared();
        if (continueButton.isEnabled()) {
            continueButton.click();
        }
    }

    private List<String> getUploadErrors() {
        return uploadErrors.stream().map(WebElement::getText).collect(toList());
    }

    public void checkUploadErrors(Matcher matcher) {
        assertThat("список ошибок загрузки excel файла не соответствует ожиданиям", getUploadErrors(), matcher);
    }
}
