package ru.yandex.autotests.direct.web.pages.banners.blocks.edit.bem;

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

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

import ru.yandex.autotests.direct.web.objects.banners.McBannerInfoWeb;
import ru.yandex.autotests.direct.web.objects.imagead.ImageAdWeb;
import ru.yandex.autotests.direct.web.pages.ExtendedHtmlElement;
import ru.yandex.autotests.direct.web.util.JavaScriptActions;
import ru.yandex.autotests.direct.web.util.StringHelper;
import ru.yandex.autotests.direct.web.util.testinterfaces.IWebFrom;
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.TextInput;

import static ch.lambdaj.Lambda.on;
import static com.google.common.collect.Iterables.getLast;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.fillHrefWithScheme;
import static ru.yandex.autotests.direct.web.util.beanutils.BeanFieldsSetter.inAccordanceWith;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

@FindBy(xpath = ".//div[contains(@class, 'b-edit-banner2 ')]")
public class McBannerBlockBem extends ExtendedHtmlElement implements IWebFrom<McBannerInfoWeb> {

    @Name("Кнопка изменения графического объявления")
    @FindBy(xpath = ".//div[contains(@class, 'b-image-add-loader')]//button")
    private Button editImageAdButton;

    @Name("Метка 'объявление'")
    @FindBy(xpath = ".//div[@class='b-edit-banner2__label-text']")
    private WebElement bannerLabel;

    @Name("Селект выбора протокола URL")
    @FindBy(css = "span.b-href-control__protocol select")
    private SelectBEM hrefProtocolSelect;

    @Name("Картинка из графического объявления")
    @FindBy(xpath = ".//div[contains(@class,'b-edit-banner2__image-ad-loader')]")
    private WebElement imageAdPicture;

    @Name("Ссылка на сайт")
    @FindBy(xpath = ".//span[contains(@class, 'b-href-control')]//input")
    private TextInput href;

    @Override
    public void fillParameters(McBannerInfoWeb bean) {
        fillHref(bean.getHref());
        fillImageAdPictureAndSave(bean.getImageAd());
    }

    @Override
    public void checkParameters(McBannerInfoWeb expectedBean) {
        assertThat("баннер соответствует ожиидаемому", getFormFieldsAccording(expectedBean),
                beanDiffer(expectedBean));
    }

    @Override
    public McBannerInfoWeb getFormFieldsAccording(McBannerInfoWeb expectedBean) {
        return inAccordanceWith(expectedBean).forNew(McBannerInfoWeb.class)
                .set("href", this, on(McBannerBlockBem.class).getHref())
                .set("imageAd", this, on(McBannerBlockBem.class).getImageAd())
                .set("bannerId", this, on(McBannerBlockBem.class).getBannerId())
                .getActualBean();
    }

    public Long getBannerId() {
        return getLast(StringHelper.getNumericDataFromText(bannerLabel.getAttribute("id")));
    }

    private void fillHref(String text) {
        if (text == null) {
            return;
        }
        href.getWrappedElement().click();
        fillHrefWithScheme(href, hrefProtocolSelect, text, false);
        new JavaScriptActions(config).fireKeyUpEvent(href.getWrappedElement());
        new JavaScriptActions(config).fireChangeEvent(href.getWrappedElement());
        new JavaScriptActions(config).fireBlurEvent(href.getWrappedElement());
    }

    public void fillImageAdPictureAndSave(ImageAdWeb imgAd) {
        if (imgAd == null) {
            return;
        }
        editImageAdButton.click();
        ImagePopupSteps.getInstance(ImagePopupSteps.class, config).loadAdImage(imgAd);
    }

    public String getHref() {
        return href.getText().equals("") ? "" :
                hrefProtocolSelect.getSelectedText() + href.getText();
    }

    public ImageAdWeb getImageAd() {
        Pattern pattern = Pattern.compile("hash\":\"(.*?)\"");
        Matcher matcher = pattern.matcher(imageAdPicture.getAttribute("data-bem"));
        matcher.find();
        ImageAdWeb imageAd = new ImageAdWeb();
        imageAd.setImageAdPictureHash(matcher.group(1));
        return imageAd;
    }
}
