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

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.yandex.direct.api.v5.reports.DateRangeTypeEnum;
import com.yandex.direct.api.v5.reports.FieldEnum;
import com.yandex.direct.api.v5.reports.FilterOperatorEnum;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.directapi.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
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.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.hamcrest.Matchers.*;
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.passport.api.core.matchers.common.IsNot.not;

/**
 * Created by onotole on 09.11.16.
 * https://st.yandex-team.ru/TESTIRT-10416
 */

/**
 * Если за нужные даты нет статистики нужно искать нового клиента.
 * https://direct.yandex.ru/registered/main?cmd=internalReports&report_id=quick_stat_from_db_by_date
 * По выбранному orderId проверяем наличие кампании на ТС и получаем ее cid:
 * m dt:ppc:all 'select cid,orderid,uid from campaigns where orderid = 13603124'
 */
@Aqua.Test
@Description("Проверка работы фильтрации по полю Query")
@Issue("https://st.yandex-team.ru/TESTIRT-9244")
@Features(ReportsFeatures.SEARCH_QUERY_PERFORMANCE_REPORT)
public class CheckFilterByQueryFieldTest {
    private static String query;
    private static final String CLIENT = ReportsLogins.CLIENT_FOR_QUERY_FILTER;

    private static final String DATE_FROM;
    private static final String DATE_TO;

    static {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Calendar dateFrom = Calendar.getInstance();
        dateFrom.add(Calendar.DATE, -80);
        DATE_FROM = dateFormat.format(dateFrom.getTime());

        Calendar dateTo = Calendar.getInstance();
        dateTo.add(Calendar.DATE, -50);
        DATE_TO = dateFormat.format(dateTo.getTime());
    }

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(Logins.LOGIN_SUPER).clientLogin(CLIENT);

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

    @BeforeClass
    public static void getSuitableQueryString() {
        ReportDefinitionMap reportDefinitionMap = new ReportDefinitionMap()
                .withDefaultSearchQueryReportWithUniqueReportName()
                .withFieldNames(FieldEnum.QUERY)
                .withDateRangeType(DateRangeTypeEnum.CUSTOM_DATE)
                .withSelectionCriteria(new SelectionCriteriaMap()
                    .withDateFrom(DATE_FROM)
                    .withDateTo(DATE_TO));
        ReportsData report = api.userSteps.reportsSteps().callReportsXml(reportDefinitionMap);
        assumeThat("вернулся непустой отчет", report.getReportsLines(), not(empty()));
        query = report.getReportsLines().get(0).getQuery();
        assumeThat("поисковый запрос не пустой", query, not(isEmptyString()));
    }

    @Test
    public void getFilteredByQueryReport() {
        ReportDefinitionMap reportDefinitionMap = new ReportDefinitionMap()
                .withDefaultSearchQueryReportWithUniqueReportName()
                .withFieldNames(FieldEnum.QUERY)
                .withDateRangeType(DateRangeTypeEnum.CUSTOM_DATE)
                .withSelectionCriteria(new SelectionCriteriaMap()
                        .withDateFrom(DATE_FROM)
                        .withDateTo(DATE_TO)
                    .withFilter(new FilterItemMap()
                        .withField(FieldEnum.QUERY)
                        .withOperator(FilterOperatorEnum.EQUALS)
                        .withValues(query)));
        ReportsData report = api.userSteps.reportsSteps().callReportsXml(reportDefinitionMap);
        assumeThat("вернулся непустой отчет при заданной фильтрации", report.getReportsLines(), not(empty()));
        assertThat("в отчете после фильтрации вернулось правильный поисковый запрос",
                report.getReportsLines().get(0).getQuery(), equalTo(query));

    }
}
