package ru.yandex.autotests.directapi.campaigns.geteventslog;

import java.util.Arrays;
import java.util.List;

import org.joda.time.DateTime;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.campaigns.CampaignFeatures;
import ru.yandex.autotests.directapi.campaigns.CampaignLogins;
import ru.yandex.autotests.directapi.common.api45.EventsLogItem;
import ru.yandex.autotests.directapi.model.banners.BannerModerationResult;
import ru.yandex.autotests.directapi.model.banners.phrases.BannerPhraseInfoMap;
import ru.yandex.autotests.directapi.model.common.Value;
import ru.yandex.autotests.directapi.model.geteventslog.EventsLogItemMap;
import ru.yandex.autotests.directapi.model.geteventslog.GetEventsLogRequestMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directapi.steps.UserSteps;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static ch.lambdaj.Lambda.extract;
import static ch.lambdaj.Lambda.on;
import static org.hamcrest.Matchers.equalTo;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;


/**
 * Created by chicos on 06.02.14.
 *
 * https://jira.yandex-team.ru/browse/TESTIRT-1400
 */
@Aqua.Test
@Features(CampaignFeatures.GET_EVENTS_LOG)
public class AllTypesSortingTest {
    protected LogSteps log = LogSteps.getLogger(this.getClass());

    private static final String clientLogin = CampaignLogins.CLIENT_RUB_WITH_ACCOUNT;
    private static final Currency CLIENT_CURRENCY = Currency.RUB;

    private static EventsLogItemMap event1;
    private static EventsLogItemMap event2;
    private static EventsLogItemMap event3;
    private static EventsLogItemMap event4;
    private static EventsLogItemMap event5;
    private static EventsLogItemMap event6;
    private static EventsLogItemMap event7;

    private static String timestamp1;
    private static List<String> expectedTypes;

    @ClassRule
    public static ApiSteps api = new ApiSteps().version(104).as(clientLogin);

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

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

    @BeforeClass
    public static void prepareEvents() {
        int accountId = api.userSteps.financeSteps().getAccountID(clientLogin);

        Long campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(clientLogin);

        final UserSteps.AdGroupCreationResult adGroupCreationResult =
                api.userSteps.addCompletedAdGroupAndReturnCreationResult(campaignId);

        Long adId = adGroupCreationResult.getAdIds()[0];

        BannerPhraseInfoMap phrase = api.userSteps.creationResultToBannerPhraseInfo(campaignId, adGroupCreationResult);

        timestamp1 = api.userSteps.changesSteps().getTimestamp();
        event1 = new EventsLogItemMap(api.type()).moneyInAccountEvent(accountId, 123f);
        api.userSteps.eventLogFakeSteps().addEvents(event1);

        event2 = new EventsLogItemMap(api.type()).moneyWarningAccountEvent(accountId, 715f);
        api.userSteps.eventLogFakeSteps().addEvents(event2);

        event3 = new EventsLogItemMap(api.type()).moneyOutAccountEvent(accountId);
        api.userSteps.eventLogFakeSteps().addEvents(event3);

        String timestamp4 = api.userSteps.changesSteps().getTimestamp();
        event4 = new EventsLogItemMap(api.type()).bannerModeratedEvent(
                campaignId.intValue(), adId, BannerModerationResult.ACCEPTED, Value.YES);
        api.userSteps.eventLogFakeSteps().addEvents(event4);

        String timestamp5 = api.userSteps.changesSteps().getTimestamp();
        event5 = new EventsLogItemMap(api.type()).warnPlaceEvent(phrase, "12");
        api.userSteps.eventLogFakeSteps().addEvents(event5);

        String timestamp7 = api.userSteps.changesSteps().getTimestamp();
        event6 = new EventsLogItemMap(api.type()).campaignFinishedEvent(campaignId.intValue(), DateTime.now().toDate());
        api.userSteps.eventLogFakeSteps().addEvents(event6);

        String timestamp9 = api.userSteps.changesSteps().getTimestamp();
        event7 = new EventsLogItemMap(api.type()).pausedByDayBudgetEvent(campaignId.intValue(), timestamp9);
        api.userSteps.eventLogFakeSteps().addEvents(event7);

        expectedTypes = Arrays.asList((String) event1.get(EventsLogItemMap.EVENT_TYPE),
                (String) event2.get(EventsLogItemMap.EVENT_TYPE),
                (String) event3.get(EventsLogItemMap.EVENT_TYPE),
                (String) event4.get(EventsLogItemMap.EVENT_TYPE),
                (String) event5.get(EventsLogItemMap.EVENT_TYPE),
                (String) event6.get(EventsLogItemMap.EVENT_TYPE),
                (String) event7.get(EventsLogItemMap.EVENT_TYPE));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("5506")
    public void getEventsSorting() {
        EventsLogItem[] events = api.userSteps.getEventsLogSteps().getEventsLog(
                new GetEventsLogRequestMap(api.type())
                        .withTimestampFrom(timestamp1)
                        .withCurrency(CLIENT_CURRENCY)
        );
        List<String> types = extract(events, on(EventsLogItem.class).getEventType());

        assertThat("сортировка событий совпадает с ожидаемой (по ID события)", types, equalTo(expectedTypes));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("5507")
    public void getEventsSortingWithLastEventOnly() {
        //https://jira.yandex-team.ru/browse/DIRECT-28851
        EventsLogItem[] events = api.userSteps.getEventsLogSteps().getEventsLog(
                new GetEventsLogRequestMap(api.type())
                        .withLastEventOnly(Value.YES)
                        .withTimestampFrom(timestamp1)
                        .withCurrency(CLIENT_CURRENCY)
        );
        List<String> types = extract(events, on(EventsLogItem.class).getEventType());

        assertThat("сортировка событий совпадает от ожидаемой (по ID события)",
                types, equalTo(expectedTypes));
    }
}
