package ru.yandex.autotests.directapi.reports.searchquery;

import com.yandex.direct.api.v5.reports.FieldEnum;
import com.yandex.direct.api.v5.reports.ReportTypeEnum;
import org.joda.time.DateTime;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5Error;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.api5.reports.*;
import ru.yandex.autotests.directapi.reports.ReportsFeatures;
import ru.yandex.autotests.directapi.reports.ReportsLogins;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

/**
 * Created by gerdler on 07.12.16.
 * https://st.yandex-team.ru/TESTIRT-10479
 */
@Aqua.Test
@Features(ReportsFeatures.SEARCH_QUERY_PERFORMANCE_REPORT)
@Description("Проверка ответа сервиса при запросе отчета за период выходящий за пределы окна и за период включающий границу окна")
@Issue("https://st.yandex-team.ru/DIRECT-56778")
public class SearchQueryReportSlidingWindowTest {
    public static DateTime validBoundaryDay = DateTime.now().minusDays(179); // окно для SEARCH_QUERY_PERFORMANCE_REPORT 180 дней включая текущий
    public static DateTime invalidBoundaryDay = validBoundaryDay.minusDays(1);

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(Logins.SUPER_LOGIN).clientLogin(ReportsLogins.REPORT_CLIENT_FOR_SLIDING_WINDOW);

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();

    @Rule
    public Trashman trasher = new Trashman(api);

    @Test
    public void successGetSearchQueryPerformanceReportForPeriod90DaysAgo() {
        ReportsData reportsData = api.userSteps.reportsSteps().callReportsXml(
                new ReportDefinitionMap()
                        .withDefaultSearchQueryReportWithUniqueReportName()
                        .withCustomDates(validBoundaryDay, validBoundaryDay)
        );
        assertThat("отчет получен", reportsData, notNullValue());
    }

    @Test
    public void successGetSearchQueryPerformanceReportForPeriodWithStartDateEarlyThan90DaysAgo() {
        ReportsData reportsData = api.userSteps.reportsSteps().callReportsXml(
                new ReportDefinitionMap()
                        .withDefaultSearchQueryReportWithUniqueReportName()
                        .withCustomDates(invalidBoundaryDay, validBoundaryDay)
        );
        assertThat("отчет получен", reportsData, notNullValue());
    }

    @Test
    public void tryGetSearchQueryPerformanceReportForPeriodEarlyThan90DaysAgo() {
        api.userSteps.reportsSteps().expectXmlErrorOnReports(
                new ReportDefinitionMap()
                        .withDefaultSearchQueryReportWithUniqueReportName()
                        .withCustomDates(invalidBoundaryDay, invalidBoundaryDay),
                new Api5Error(
                        4001,
                        Api5ErrorDetails.SEARCH_QUERY_PERFORMANCE_REPORT_DATE_RANGE_OUT_OF_SLIDING_WINDOW,
                        ReportTypeEnum.SEARCH_QUERY_PERFORMANCE_REPORT,
                        capitalize(SelectionCriteriaMap.DATE_TO),
                        validBoundaryDay.toString(ReportsData.DATE_FORMAT)
                )
        );
    }

    @Test
    public void compareReportsDataForPeriodThreeYearsAgo() {
        DateTime dateFrom = validBoundaryDay.minusDays(7);
        DateTime dateTo = validBoundaryDay.plusDays(7);
        ReportsData expectedReportsData = api.userSteps.reportsSteps().callReportsXml(
                getReportDefinitionMapToCompareBorderStat(validBoundaryDay, dateTo)
        );
        assumeThat("вернулся непустой отчет", expectedReportsData.getReportsLines(), not(empty()));
        ReportsData reportsData = api.userSteps.reportsSteps().callReportsXml(
                getReportDefinitionMapToCompareBorderStat(dateFrom, dateTo)
        );
        assertThat("получили правильные данные", reportsData.getReportsLines(), beanDiffer(expectedReportsData.getReportsLines()));
    }

    private ReportDefinitionMap getReportDefinitionMapToCompareBorderStat(DateTime dateFrom, DateTime dateTo) {
        return new ReportDefinitionMap()
                .withDefaultSearchQueryReportWithUniqueReportName()
                .withCustomDates(dateFrom, dateTo)
                .withFieldNames(FieldEnum.AD_GROUP_ID, FieldEnum.QUERY, FieldEnum.CLICKS, FieldEnum.IMPRESSIONS)
                .withPage(new PageMap().withLimit(100L))
                .withOrderBy(
                        new OrderByMap().withField(FieldEnum.AD_GROUP_ID),
                        new OrderByMap().withField(FieldEnum.QUERY)
                );
    }
}
