package ru.yandex.autotests.direct.api.campaigns.update.contentpromotion.settings;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import com.yandex.direct.api.v5.campaignsext.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaignsext.ContentPromotionCampaignFieldEnum;
import com.yandex.direct.api.v5.campaignsext.ContentPromotionCampaignSettingGet;
import com.yandex.direct.api.v5.campaignsext.ContentPromotionCampaignSettingsEnum;
import com.yandex.direct.api.v5.campaignsext.ContentPromotionCampaignSettingsGetEnum;
import com.yandex.direct.api.v5.campaignsext.GetResponse;
import com.yandex.direct.api.v5.general.YesNoEnum;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Before;
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.api.campaigns.CampaignsFeatures;
import ru.yandex.autotests.direct.api.campaigns.CampaignsLogins;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.darkside.datacontainers.jsonrpc.fake.CampaignFakeInfo;
import ru.yandex.autotests.directapi.model.api5.campaignsext.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.CampaignsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignSettingMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.campaigns.Status;
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.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
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 pavryabov on 23.11.15.
 * https://st.yandex-team.ru/TESTIRT-7756
 */
@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@Issue("https://st.yandex-team.ru/DIRECT-44876")
@Description("Проверка настройки REQUIRE_SERVICING поля Settings для динамических текстовых кампаний")
@RunWith(Parameterized.class)
public class UpdateManagerAssistanceTest {

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

    @ClassRule
    public static ApiSteps api = new ApiSteps();

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

    private static final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    private static DateTime lastChange = DateTime.now().minusDays(5);
    private Long campaignID;
    private CampaignFakeInfo campaignInfo;
    private List<ContentPromotionCampaignSettingGet> settings;

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

    @Parameterized.Parameter(0)
    public String login;

    @Parameterized.Parameter(1)
    public YesNoEnum settingValue;

    @Parameterized.Parameter(2)
    public YesNoEnum expectedValue;

    @Parameterized.Parameters(name = "login = {0}, value = {1}")
    public static Collection testData() {
        Object[][] data = new Object[][]{
                {CampaignsLogins.SERV_CLIENT, YesNoEnum.NO, YesNoEnum.YES},
                {CampaignsLogins.SERV_CLIENT, YesNoEnum.YES, YesNoEnum.YES},
                {CampaignsLogins.GET_CLIENT, YesNoEnum.YES, YesNoEnum.NO}
        };
        return Arrays.asList(data);
    }

    @Before
    @Step("Подготовим данные для теста")
    public void prepareCampaign() {
        YesNoEnum addSetting = (settingValue.equals(YesNoEnum.NO)) ? (YesNoEnum.YES) : (YesNoEnum.NO);
        log.info("Создадим кампанию с настройкой REQUIRE_SERVICING = " + addSetting);
        List<Long> ids = api.as(login).userSteps.campExtSteps().campaignsAddWithCheck(
                new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withContentPromotionCampaign(new ContentPromotionCampaignAddItemMap()
                                .defaultContentPromotionCampaign()
                                .withSettings(new ContentPromotionCampaignSettingMap()
                                        .withOption(ContentPromotionCampaignSettingsEnum.REQUIRE_SERVICING)
                                        .withValue(addSetting))));
        campaignID = ids.get(0);

        log.info("Выставим фейково статусы модерации, статусы синхронизации с БК, сдвинем время последнего изменения");
        CampaignFakeInfo campaign = new CampaignFakeInfo();
        campaign.setCampaignID(campaignID.intValue());
        campaign.setStatusModerate(Status.YES);
        campaign.setStatusPostModerate(Status.ACCEPTED);
        campaign.setStatusBsSynced(Status.YES);
        campaign.setLastChange(lastChange.toString());
        api.userSteps.campaignFakeSteps().fakeCampaignParams(campaign);

        log.info("Обновим значение настройку REQUIRE_SERVICING на " + settingValue);
        api.userSteps.campExtSteps().campaignsUpdate(
                new UpdateRequestMap().withCampaigns(
                        new CampaignUpdateItemMap()
                                .withId(campaignID)
                                .withContentPromotionCampaign(new ContentPromotionCampaignUpdateItemMap()
                                        .withSettings(new ContentPromotionCampaignSettingMap()
                                                .withOption(ContentPromotionCampaignSettingsEnum.REQUIRE_SERVICING)
                                                .withValue(settingValue)))));
        GetResponse getResponse = api.userSteps.campExtSteps().campaignsGet(
                new GetRequestMap()
                        .withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                                .withIds(campaignID))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withContentPromotionCampaignFieldNames(ContentPromotionCampaignFieldEnum.SETTINGS));
        assumeThat("вернулась 1 кампания", getResponse.getCampaigns(), hasSize(1));
        assumeThat("получили текстовые параметры кампании", getResponse.getCampaigns().get(0).getContentPromotionCampaign(),
                notNullValue());
        settings = getResponse.getCampaigns().get(0).getContentPromotionCampaign().getSettings();
        assumeThat("вернулись Settings кампании", settings, notNullValue());

        campaignInfo = api.userSteps.campaignFakeSteps().fakeGetCampaignParams(campaignID);
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("956")
    public void settingValueTest() {
        List<YesNoEnum> value = settings.stream()
                .filter(setting -> setting.getOption().equals(ContentPromotionCampaignSettingsGetEnum.REQUIRE_SERVICING))
                .map(setting -> setting.getValue()).collect(Collectors.toList());
        assertThat("вернулся ожидаемый параметр", value, equalTo(Arrays.asList(expectedValue)));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("1206")
    public void statusBsSyncedTest() {
        log.info("Проверим статус синхронизации с БК");
        assertThat("статус синхронизации с БК после модификации настроек кампании",
                campaignInfo.getStatusBsSynced(), equalTo(Status.NO));//Bug - DIRECT-46718
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("955")
    public void lastChangeTest() {
        log.info("Проверим время последнего изменнеия кампании");
        assumeThat("время последнего изменения кампании", campaignInfo.getLastChange(), notNullValue());
        LocalDate actualDate = formatter.parseLocalDate(campaignInfo.getLastChange());

        assertThat("время последнего изменения кампании после модификации настроек", actualDate,
                equalTo(LocalDate.now()));
    }
}
