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

import java.util.Date;
import java.util.List;

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

import ru.yandex.autotests.direct.web.data.SelectInputMethod;
import ru.yandex.autotests.direct.web.data.statistic.NewReportInfoWeb;
import ru.yandex.autotests.direct.web.data.statistic.ReportWizardColumnsInfoWeb;
import ru.yandex.autotests.direct.web.data.statistic.ReportWizardSlicesInfoWeb;
import ru.yandex.autotests.direct.web.pages.statistic.blocks.StatisticsReportWizardColumnsBlock;
import ru.yandex.autotests.direct.web.pages.statistic.blocks.StatisticsReportWizardSlicesBlock;
import ru.yandex.autotests.direct.web.pages.statistic.chart.StatisticChart;
import ru.yandex.autotests.direct.web.util.DirectWebError;
import ru.yandex.autotests.direct.web.webelements.bem.CalendarReportWizardInputBEM;
import ru.yandex.autotests.direct.web.webelements.bem.CheckBoxBEM;
import ru.yandex.autotests.direct.web.webelements.bem.SelectBEM;
import ru.yandex.qatools.allure.webdriver.annotations.NamedUrl;
import ru.yandex.qatools.allure.webdriver.annotations.NamedUrls;
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 static ru.yandex.autotests.direct.web.steps.BackendSteps.toBoolean;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.fillSelect;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.setCheckboxState;

@NamedUrls({
        @NamedUrl(name = "campaign.stat", url = "/registered/main.pl?cmd=showStat&cid={1}&interface=std"),
        @NamedUrl(name = "campaign.stat.for.login",
                url = "/registered/main.pl?cmd=showStat&cid={1}&ulogin={2}&interface=std"),
        @NamedUrl(name = "campaign.stat.light", url = "cmd=showStat&detail=Yes&cid={1}" +
                "&showCampStat=cmd&types=days&target_all=1"),
        @NamedUrl(name = "campaign.stat.light.for.login", url = "/registered/main.pl?c" +
                "md=showStat&detail=Yes&cid={1}&ulogin={2}&showStat=cmd&types=days&target_all=1"),
        @NamedUrl(name = "campaign.stat.with.params", url = "/registered/main.pl?cmd=showStat&cid={1}&{2}"),
        @NamedUrl(name = "all.campaigns.stat.for.login",
                url = "/registered/main.pl?cmd=showStat&ulogin={1}&stat_type=campdate"),
        @NamedUrl(name = "wizard.for.campaign.and.login",
                url = "/registered/main.pl?cmd=showStat&cid={1}&ulogin={2}&stat_type=custom&target_all=1")
})
public class StatisticsReportWizardPageBEM extends BasePageObject {
    @Name("Группировка")
    @FindBy(xpath = ".//div[contains(@class,'b-statistics-form__period-group')]//select")
    private SelectBEM filterGroup;

    @Name("Строк на странице")
    @FindBy(name = "page_size")
    private SelectBEM pageSize;

    @Name("Скрыть/показать выбранные срезы,столбцы и фильтры")
    @FindBy(xpath = "(.//span[contains(@class,'b-statistics-form__expander')])[1]//span[@class='link__inner']")
    private WebElement showAndHideColumnsAndSlices;

    @Name("Кнопка 'Показать'")
    @FindBy(xpath = ".//button[contains(@class, 'b-statistics-form__submit-button')]")
    private Button showButton;

    @Name("Кнопка 'Сохранить отчет'")
    @FindBy(xpath = ".//div[contains(@class, 'b-statistics-form__dropdown-report-button')]//button")
    private Button saveReport;

    @Name("Таблица со статистикой")
    @FindBy(xpath = "(.//table[contains(@class,'b-stat-table')])[1]")
    private WebElement statisticsTable;

    @Name("кнопка сравнить периоды")
    @FindBy(xpath = ".//label[contains(@class,'b-statistics-form__compare-toggler')]//input")
    private WebElement comparePeriods;

    @Name("НДС")
    @FindBy(name = "with_nds")
    private CheckBoxBEM withVat;

    @Name("Календарь")
    @FindBy(xpath = ".//button[contains(@class,'b-date-range-picker__super-button')]")
    private Button openCalendarButton;

    @Name("Список ссылок на баннеры для статистики по мастеру отчетов")
    @FindBy(css = "div.b-group-preview2-opener span.link__inner")
    private List<Link> bannerPreviewLinks;

    @Name("Кнопка 'Показать график'")
    @FindBy(css = ".b-charts-manager__switcher")
    private Button chartSwitcher;

    @Name("Модель атрибуции")
    @FindBy(xpath = ".//select[@name='attribution_model']")
    private SelectBEM attributionModelSelect;

    private CalendarReportWizardInputBEM calendar;

    private StatisticChart statisticChart;

    StatisticsReportWizardSlicesBlock slicesBlock;
    StatisticsReportWizardColumnsBlock columnsBlock;

    public void clickShow() {
        showButton.click();
    }

    public void clickOpenColumnsAndSlices() {
        showAndHideColumnsAndSlices.click();
    }

    public void clickComparePeriods() {
        comparePeriods.click();
    }

    public WebElement getStatisticsTable() {
        return statisticsTable;
    }

    public void fillStatisticRequestInfo(NewReportInfoWeb info) {
        fillDate(info.getStartDate(), info.getEndDate());
        fillSelect(filterGroup, info.getGroupByDate(), SelectInputMethod.BY_VALUE);
        fillSelect(pageSize, info.getLinesPerPage(), SelectInputMethod.BY_VALUE);
        setCheckboxState(withVat, toBoolean(info.getIncludeVat()));
        if (info.getAttributionModel() != null) {
            fillSelect(attributionModelSelect, info.getAttributionModel().getValue(), SelectInputMethod.BY_VALUE);
        }
        //Эти галки стоят по умолчанию, они блокирует возможность поставить галку напротив пункта "Место клика"
        //Отключаем их принудительно перед заполнением формы
        columnsBlock.fillShows(false);
        columnsBlock.fillCtr(false);
        fillSlicesParameters(info.getReportWizardSlicesInfoWeb());
        fillColumnsParameters(info.getReportWizardColumnsInfoWeb());
    }

    private void fillDate(Date dateFrom, Date dateTo) {
        if (dateFrom == null || dateTo == null) {
            return;
        }
        openCalendarButton.click();
        calendar.fillDate(dateFrom, dateTo);
    }

    private void fillSlicesParameters(ReportWizardSlicesInfoWeb filter) {
        if (filter == null) {
            return;
        }
        slicesBlock.fillAge(filter.getAge());
        slicesBlock.fillAdgroup(filter.getAdgroup());
        slicesBlock.fillBanner(filter.getBanner());
        slicesBlock.fillBannerImageType(filter.getBannerImageType());
        slicesBlock.fillBannerType(filter.getBannerType());
        slicesBlock.fillClickPlace(filter.getClickPlace());
        slicesBlock.fillContextCond(filter.getContextCond());
        slicesBlock.fillRetargetingCoef(filter.getRetargetingCoef());
        slicesBlock.fillDeviceType(filter.getDeviceType());
        slicesBlock.fillGender(filter.getGender());
        slicesBlock.fillImageSize(filter.getImageSize());
        slicesBlock.fillPage(filter.getPage());
        slicesBlock.fillPageGroup(filter.getPageGroup());
        slicesBlock.fillPhysicalRegion(filter.getPhysicalRegion());
        slicesBlock.fillPosition(filter.getPosition());
        slicesBlock.fillRegion(filter.getRegion());
        slicesBlock.fillSsp(filter.getSsp());
        slicesBlock.fillTags(filter.getTags());
        slicesBlock.fillTargetType(filter.getTargetType());
    }

    private void fillColumnsParameters(ReportWizardColumnsInfoWeb filter) {
        if (filter == null) {
            return;
        }
        columnsBlock.fillAverageClickPosition(filter.getAverageClickPosition());
        columnsBlock.fillAverageShowsPosition(filter.getAverageShowsPosition());
        columnsBlock.fillAverageSum(filter.getAverageSum());
        columnsBlock.fillBounceRatio(filter.getBounceRatio());
        columnsBlock.fillClicks(filter.getClicks());
        columnsBlock.fillConversion(filter.getConversion());
        columnsBlock.fillConversionsNum(filter.getConversionsNum());
        columnsBlock.fillCtr(filter.getCtr());
        columnsBlock.fillDepth(filter.getDepth());
        columnsBlock.fillGoalCost(filter.getGoalCost());
        columnsBlock.fillGoalRoi(filter.getGoalRoi());
        columnsBlock.fillIncome(filter.getIncome());
        columnsBlock.fillShows(filter.getShows());
        columnsBlock.fillSum(filter.getSum());
        columnsBlock.fillAgoalsProfit(filter.getAgoalsProfit());
    }

    private Link getBannerPreviewLink(Long bannerId) {
        return bannerPreviewLinks.stream().filter(b -> b.getText().contains(bannerId.toString())).findFirst()
                .orElseThrow(() -> new DirectWebError("Не найдено превью баннера " + bannerId));
    }

    public void clickOnBannerPreviewLink(Long bannerId) {
        getBannerPreviewLink(bannerId).click();
    }

    public void clickOnChartSwitcher() {
        chartSwitcher.click();
    }

    public StatisticChart onStatisticChart() {
        return statisticChart;
    }
}
