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

import java.util.Arrays;
import java.util.Collection;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.utils.model.ShardNumbers;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.direct.utils.textresource.TextResourceFormatter;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.methods.Method;
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.geteventslog.EventName;
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.irt.testutils.allure.LogSteps;
import ru.yandex.autotests.irt.testutils.json.JsonUtils;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.hasItems;
import static ru.yandex.autotests.direct.utils.matchers.BeanEquals.beanEquals;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Migrated from old school project (api4l)
 * <br/>
 * Created by chicos on 06.02.14.<br/>
 * https://jira.yandex-team.ru/browse/TESTIRT-1400
 * для клиентов поле Logins игнорируется и возвращается все события по клиенту
 */
@Aqua.Test
@Features(CampaignFeatures.GET_EVENTS_LOG)
@Tag(TagDictionary.TRUNK)
@RunWith(Parameterized.class)
public class GetEventsRequestValidateLoginsForClientTest {

    private LogSteps log = LogSteps.getLogger(this.getClass());

    private static final String CLIENT_LOGIN = CampaignLogins.SELF_CLIENT;
    private static final String NO_RIGHT_LOGIN = CampaignLogins.SELF_CLIENT_SHARD_2;
    private static final Currency CLIENT_CURRENCY = Currency.RUB;

    private static String timestampBefore;
    private static EventsLogItemMap finishedEvent;

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

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

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

    @Parameterized.Parameter
    public Object logins;

    @Parameterized.Parameters(name = "logins = {0}")
    public static Collection timestampTemplate() {
        Object[][] data = new Object[][]{
                {null},
                {new String[]{null}},
                {CLIENT_LOGIN},
                {Arrays.asList()},
                {Arrays.asList(NO_RIGHT_LOGIN)},
                {Arrays.asList(CLIENT_LOGIN, NO_RIGHT_LOGIN)}
        };
        return Arrays.asList(data);
    }

    @BeforeClass
    public static void prepareEvent() {
        api.userSteps.clientFakeSteps().reshardUserWithLock(NO_RIGHT_LOGIN, ShardNumbers.EXTRA_SHARD);
        Long campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(CLIENT_LOGIN);

        timestampBefore = api.userSteps.changesSteps().getTimestamp();
        finishedEvent = new EventsLogItemMap(api.type())
                .campaignFinishedEvent(campaignId.intValue(), DateTime.now().toDate());
        api.userSteps.eventLogFakeSteps().addEvents(finishedEvent);
        finishedEvent.withTimestamp(null)
                .withEventName(TextResourceFormatter.resource(EventName.CAMPAIGN_FINISHED).toString());
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("5606")
    public void getEventByLoginFieldIgnore() throws ParseException {
        GetEventsLogRequestMap getEventsLogRequestMap = new GetEventsLogRequestMap(api.type())
                .withCurrency(CLIENT_CURRENCY)
                .withTimestampFrom(timestampBefore);

        JSONObject eventsLogBean = (JSONObject) (new JSONParser()
                .parse(JsonUtils.toString(getEventsLogRequestMap.getBean())));
        eventsLogBean.put(StringUtils.capitalize(GetEventsLogRequestMap.LOGINS), logins);

        EventsLogItem[] events = api.userSteps.getEventsLogSteps()
                .jsonClient()
                .invokeMethod(
                        Method.GET_EVENTS_LOG,
                        new GetEventsLogRequestMap(eventsLogBean)
                                .getBean()
                );

        assertThat("присутствует событие", Arrays.asList(events),
                hasItems(beanEquals((EventsLogItem) finishedEvent.getBean())));
    }
}
