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

import org.apache.commons.lang3.StringUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.support.FindBy;
import ru.yandex.autotests.direct.web.data.banners.GroupChangesBlockTabs;
import ru.yandex.autotests.direct.web.data.banners.GroupChangesInfo;
import ru.yandex.autotests.direct.web.data.contactinfo.Regions;
import ru.yandex.autotests.direct.web.data.textresources.EditBannerResource;
import ru.yandex.autotests.direct.web.objects.banners.BannerInfoWeb;
import ru.yandex.autotests.direct.web.objects.banners.commons.SiteLinkInfoWeb;
import ru.yandex.autotests.direct.web.objects.retargeting.RetargetingConditionWeb;
import ru.yandex.autotests.direct.web.pages.banners.blocks.edit.AdjustPhraseBlock;
import ru.yandex.autotests.direct.web.pages.banners.blocks.edit.ChoosePhraseBlock;
import ru.yandex.autotests.direct.web.pages.mediaplans.blocks.EditMediaplanBlock;
import ru.yandex.autotests.direct.web.pages.mediaplans.blocks.GroupChangesBlock;
import ru.yandex.autotests.direct.web.steps.CommonSteps;
import ru.yandex.autotests.direct.web.util.DirectWebError;
import ru.yandex.qatools.allure.webdriver.pages.BasePageObject;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.Button;
import ru.yandex.qatools.htmlelements.element.Link;

import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.MatcherAssert.assertThat;

/**
 * User: alexey-n
 * Date: 26.08.13
 * Time: 16:55
 */
public class MultiEditMediaplanPage extends BasePageObject {

    @Name("Кнопка далее")
    @FindBy(xpath = ".//input[contains(@class, 'validate__submit')]")
    private Button nextButton;

    @Name("Кнопка назад")
    @FindBy(xpath = ".//input[contains(@class, 'validate__back')]")
    private Button prevButton;

    @Name("Кнопка групповых действий")
    @FindBy(id = "multiedit_functions_link")
    private Link groupChangesLink;

    private AdjustPhraseBlock adjustPhraseBlock;

    private ChoosePhraseBlock choosePhraseBlock;

    private Long mediaplanID;

    private List<EditMediaplanBlock> mediaplanBlockList;

    private GroupChangesBlock groupChangesBlock;

    private GroupChangesBlock getGroupChangesBlock() {
        groupChangesBlock.setConfig(config);
        return groupChangesBlock;
    }

    public void fillGroupEditParameters(GroupChangesInfo groupChangesInfo) {
        groupChangesLink.click();
        getGroupChangesBlock().fill(groupChangesInfo);
    }

    public void openGroupChangesTab(GroupChangesBlockTabs groupChangesBlockTabs) {
        groupChangesLink.click();
        getGroupChangesBlock().openGroupChangesTab(groupChangesBlockTabs);
    }

    public void checkGroupChangesSiteLinksPopupParameters(SiteLinkInfoWeb[] siteLinks) {
        getGroupChangesBlock().checkSiteLinks(siteLinks);
    }


    public void fillMediaplanParameters(Long mediaplanId, BannerInfoWeb bannerInfo) {
        EditMediaplanBlock mediaplanBlock = getEditMediaplanBlock(mediaplanId);
        if (mediaplanBlock == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана");
        } else {
            mediaplanBlock.fillParameters(bannerInfo);
        }
    }

    public void checkMinusKeyWordsPopup(Long mediaplanID, Matcher matcher) {
        EditMediaplanBlock mediaplanBlock = getEditMediaplanBlock(mediaplanID);
        if (mediaplanBlock == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана");
        } else {
            mediaplanBlock.checkMinusKeyWordsPopup(matcher);
        }
    }

    public void checkMediaplanParameters(BannerInfoWeb expectedInfo) {
        EditMediaplanBlock mediaplanBlock = getEditMediaplanBlock(mediaplanID);
        if (mediaplanBlock == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана");
        } else {
            mediaplanBlock.checkParameters(expectedInfo);
        }
    }

    public void checkMediaplanAdBlock(Long mediaplanID, Matcher matcher) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanID);
        assertThat("блок редактирования медиаплана с ID = " + mediaplanID +
                " не соответствует ожиданиям", block, matcher);
    }

    public void forMediaplanID(Long mediaplanID) {
        this.mediaplanID = mediaplanID;
    }

    private EditMediaplanBlock getEditMediaplanBlock(Long mediaplanId) {
        EditMediaplanBlock block = mediaplanBlockList.stream()
                .filter(t -> t.getBannerId().equals(mediaplanId))
                .findFirst().orElseThrow(() -> new DirectWebError("Не найден блок медиаплана " + mediaplanId));
        block.setConfig(config);
        return block;
    }

    public void clickNextButton() {
        nextButton.click();
    }

    public void clickPrevButton() {
        prevButton.click();
    }

    public void checkMediaplanPhraseList(Matcher matcher, Long mediaplanId) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanId);
        if (block == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана.");
        } else {
            block.checkPhraseList(matcher);
        }
    }

    public void adjustPhrase(Long mediaplanId, String phrase) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanId);
        if (block == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана.");
        } else {
            block.clickAdjustPhrase(phrase);
        }
    }

    //Подобрать фразы
    public void choosePhrase(Long mediaplanId, String phrase) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanId);
        if (block == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана.");
        } else {
            block.clickChoosePhrase(phrase);
        }
    }

    public void checkAdjustPhraseWindow(String phrase, String regions) {
        String mainWindowHref = config.getDriver().getCurrentUrl();
        prevButton.click();
        CommonSteps.getInstance(CommonSteps.class, config).setDriverToOperateWithPage(mainWindowHref);
        adjustPhraseBlock.checkPhrase(phrase);
        List<String> regionTextList = new ArrayList<>();
        for (String regionID : regions.split(",")) {
            regionTextList.add(Regions.getRegionByID(regionID).toString());
        }
        adjustPhraseBlock.checkRegions(StringUtils.join(regionTextList, ", "));
    }

    public void checkChoosePhraseWindow(String phrase, String regions) {
        CommonSteps.getInstance(CommonSteps.class, config)
                .setDriverToOperateWithPage(EditBannerResource.CHOOSE_PHRASE_WINDOW_TITLE.toString());
        choosePhraseBlock.checkPhrases(phrase);
        choosePhraseBlock.checkRegions(regions);
    }

    public void openPhraseActionPopup(Long mediaplanID) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanID);
        if (block == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана.");
        } else {
            block.openPhraseActionPopup();
        }
    }

    public void checkDomain(Long mediaplanID, String domain) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanID);
        if (block == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана.");
        } else {
            block.checkDomainName(domain);
        }
    }

    public void clickOnClearMediaplanPhrasesTextInput(Long mediaplanID) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanID);
        if (block == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана.");
        } else {
            block.clickOnClearPhrasesTextInput();
        }
    }

    public void addSavedRetargetingCondition(Long mediaplanID, String conditionName) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanID);
        if (block == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана " + mediaplanID);
        } else {
            block.clickAddRetargetingCondition();
            block.addSavedRetargetingCondition(conditionName);
        }
    }

    public void deleteRetargetingCondition(Long mediaplanID, String conditionName) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanID);
        if (block == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана " + mediaplanID);
        } else {
            block.deleteCondition(conditionName);
        }
    }

    public void checkCantEditFields(Long mediaplanID, RetargetingConditionWeb conditionWeb) {
        EditMediaplanBlock block = getEditMediaplanBlock(mediaplanID);
        if (block == null) {
            throw new DirectWebError("Не найден блок редактирования медиаплана " + mediaplanID);
        } else {
            block.checkCantEditFields(conditionWeb);
        }
    }
}
