package ru.yandex.autotests.direct.api.campaigns.resume;

import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
import com.yandex.direct.api.v5.campaigns.CampaignStateGetEnum;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.api.campaigns.CampaignsFeatures;
import ru.yandex.autotests.direct.api.campaigns.CampaignsLogins;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.common.api45mng.CreateNewSubclientResponse;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.api5.Action;
import ru.yandex.autotests.directapi.model.api5.campaigns.ResumeRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.IdsCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
import ru.yandex.autotests.directapi.model.clients.ConvertType;
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.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
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;

/**
 * Created by chicos on 20.08.15.
 */
@Aqua.Test
@Features(CampaignsFeatures.RESUME)
@Description("Проверка негативных сценариев возобновления кампаний")
@Tag(TagDictionary.TRUNK)
public class ResumeCampaignsNegativeTest {
    private LogSteps log = LogSteps.getLogger(this.getClass());
    private static final String client = CampaignsLogins.SINGLE_CLIENT_RESUME;

    private static Long campaignNotSuspended;
    private static Long campaignArchived;

    private static Long campaignID;
    private static Long campaignID1;
    private static Long campaignID2;
    private static String srvClient;

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(client);

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

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

    @BeforeClass
    public static void prepareCampaigns() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);

        //Создадим сервисируемого клиента YE
        CreateNewSubclientResponse createNewSubclientResponse =
                api.as(Logins.MANAGER_GEO).wsdl(ru.yandex.autotests.directapi.common.api45mng.APIPort_PortType.class)
                        .userSteps.clientSteps().createServicedClient("subClient", Logins.MANAGER_GEO);
        assumeThat("клиент создан успешно", createNewSubclientResponse.getLogin(), notNullValue());
        srvClient = createNewSubclientResponse.getLogin();
        api.userSteps.clientFakeSteps().enableAPI(srvClient);

        api.as(client).wsdl(ru.yandex.autotests.directapi.common.api45.APIPort_PortType.class);
        campaignNotSuspended = api.userSteps.campaignSteps().addDefaultTextCampaign();
        campaignArchived = api.userSteps.campaignSteps().addDefaultTextCampaign();
        campaignID = api.userSteps.campaignSteps().addDefaultTextCampaign();
        campaignID1 = api.userSteps.campaignSteps().addDefaultTextCampaign();
        campaignID2 = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignSteps().campaignsSuspend(campaignArchived, campaignID, campaignID1, campaignID2);
        api.userSteps.campaignSteps().campaignsArchive(campaignArchived);
    }

    @Test
    @Description("Попробуем возобновить работающую кампанию")
    @ru.yandex.qatools.allure.annotations.TestCaseId("572")
    public void notSuspendedCampaignTest() {
        api.as(client).userSteps.campaignSteps().shouldGetResultOn(
                Action.RESUME,
                new ResumeRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignNotSuspended)),
                ExpectedResult.warnings(new Notification(10021,
                        Api5ErrorDetails.CAMPAIGN_NOT_SUSPENDED)));
    }

    @Test
    @Description("Попробуем возобновить архивную кампанию")
    @ru.yandex.qatools.allure.annotations.TestCaseId("573")
    public void archivedCampaignTest() {
        api.as(client).userSteps.campaignSteps().shouldGetResultOn(
                Action.RESUME,
                new ResumeRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignArchived)),
                ExpectedResult.errors(new Notification(8300, Api5ErrorDetails.UNABLE_UPDATE_ARCHIVED_CAMPAGN)));
    }

    @Test
    @Description("Возобновление двух кампаний, идентификатор одной из которых - некорректен")
    @ru.yandex.qatools.allure.annotations.TestCaseId("575")
    public void resumeMultipleCampaignsOneInvalidTest() {
        api.as(client).userSteps.campaignSteps().shouldGetResultOn(
                Action.RESUME,
                new ResumeRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignID, 123456L)),
                ExpectedResult.success(campaignID),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.CAMPAIGN_NOT_FOUND)));
    }

    @Test
    @Description("Два однинаковых идентификатора кампании в запросе")
    @ru.yandex.qatools.allure.annotations.TestCaseId("571")
    public void sameIdsInRequestTest() {
        api.as(client).userSteps.campaignSteps().shouldGetResultOn(
                Action.RESUME,
                new ResumeRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignID1, campaignID1, campaignID2)),
                ExpectedResult.warnings(
                        new Notification(10000, Api5ErrorDetails.CAMPAIGN_ID_IS_PRESENTED_MORE_THAN_ONCE_IN_REQUEST)),
                ExpectedResult.warnings(
                        new Notification(10000, Api5ErrorDetails.CAMPAIGN_ID_IS_PRESENTED_MORE_THAN_ONCE_IN_REQUEST)),
                ExpectedResult.success(campaignID2));

        CampaignGetItem campaign = api.userSteps.campaignSteps().campaignsGet(campaignID1, CampaignFieldEnum.STATE);
        assertThat("кампания остановлена несмотря на warning", campaign.getState(), equalTo(CampaignStateGetEnum.OFF));
    }

    @Test
    @Description("Проверка возможности возобновления кампании после конвертации COPY")
    @ru.yandex.qatools.allure.annotations.TestCaseId("574")
    @Ignore
    public void resumeOldCampaignAfterCopyConvertTest() {
        Long oldCampaignID = api.as(Logins.MANAGER_GEO).userSteps.campaignSteps().addDefaultTextCampaign(srvClient);

        log.info("Сконвертируем клиента методом COPY");
        api.userSteps.clientFakeSteps().convertCurrency(
                srvClient,
                Currency.RUB.toString(),
                ConvertType.COPY);

        log.info("Попробуем возобновить старую фишковую кампанию");
        api.userSteps.campaignSteps().shouldGetResultOn(
                srvClient,
                Action.RESUME,
                new ResumeRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(oldCampaignID)),
                ExpectedResult.errors(new Notification(8300, Api5ErrorDetails.UNABLE_UPDATE_ARCHIVED_CAMPAGN)));
    }
}
