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

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

import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignSettingGet;
import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignSettingsEnum;
import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignSettingsGetEnum;
import com.yandex.direct.api.v5.campaigns.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.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignSettingMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.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.direct.api.campaigns.CampaignsDeprecatedSettings.DYNAMIC_TEXT_CAMPAIGN_DEPRECATED_SETTINGS;
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
@Issue("https://st.yandex-team.ru/DIRECT-44876")
@Features(CampaignsFeatures.UPDATE)
@Description("Проверка поля Settings в динамических текстовых кампаниях")
@RunWith(Parameterized.class)
public class UpdateAndGetSettingsTest {

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

    private static final String client = CampaignsLogins.GET_SERV_CLIENT;

    private static final DateTime lastChange = DateTime.now().minusDays(5);
    private static final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

    private static Long campaignID;
    private GetResponse getResponse;
    private CampaignFakeInfo campaignInfo;

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

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

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

    @Parameterized.Parameter(0)
    public DynamicTextCampaignSettingsEnum option;

    @Parameterized.Parameter(1)
    public YesNoEnum settingValue;

    @Parameterized.Parameters(name = "option = {0}, value = {1}")
    public static Collection<Object[]> testData() {
        List<Object[]> data = new ArrayList<>();
        for (DynamicTextCampaignSettingsEnum settingsEnum : DynamicTextCampaignSettingsEnum.values()) {
            if (DYNAMIC_TEXT_CAMPAIGN_DEPRECATED_SETTINGS.contains(settingsEnum)) {
                continue;
            }
            data.add(new Object[]{settingsEnum, YesNoEnum.NO});
            data.add(new Object[]{settingsEnum, YesNoEnum.YES});
        }
        return data;
    }

    @Before
    @Step("Подготовим данные для теста")
    public void prepareCampaign() {
        YesNoEnum addSetting = (settingValue.equals(YesNoEnum.NO)) ? (YesNoEnum.YES) : (YesNoEnum.NO);
        log.info("Создадим кампанию с настройкой " + option + " = " + addSetting);
        List<Long> ids = api.userSteps.campaignSteps().campaignsAddWithCheck(
                new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withDynamicTextCampaign(new DynamicTextCampaignAddItemMap()
                                .defaultDynamicTextCampaign()
                                .withSettings(new DynamicTextCampaignSettingMap()
                                        .withOption(option)
                                        .withValue(addSetting))));
        assumeThat("создана кампания", ids, hasSize(1));
        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("Обновим значение настройку " + option + " на " + settingValue);
        api.userSteps.campaignSteps().campaignsUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignID)
                        .withDynamicTextCampaign(new DynamicTextCampaignUpdateItemMap()
                                .withSettings(new DynamicTextCampaignSettingMap()
                                        .withOption(option)
                                        .withValue(settingValue)))));
        getResponse = api.userSteps.campaignSteps().campaignsGet(
                new GetRequestMap()
                        .withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                                .withIds(campaignID))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withDynamicTextCampaignFieldNames(DynamicTextCampaignFieldEnum.SETTINGS));
        assumeThat("вернулась 1 кампания", getResponse.getCampaigns(), hasSize(1));
        assumeThat("вернулись текстовые параметры кампании", getResponse.getCampaigns().get(0).getDynamicTextCampaign(),
                notNullValue());
        assumeThat("вернулись Settings кампании",
                getResponse.getCampaigns().get(0).getDynamicTextCampaign().getSettings(), notNullValue());

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

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("953")
    public void settingValueTest() {
        // REQUIRE_SERVICING нельзя поменять с Yes на No
        if (option == DynamicTextCampaignSettingsEnum.REQUIRE_SERVICING) settingValue = YesNoEnum.YES;
        List<DynamicTextCampaignSettingGet> settings =
                getResponse.getCampaigns().get(0).getDynamicTextCampaign().getSettings();
        List<YesNoEnum> value = settings.stream()
                .filter(setting -> setting.getOption()
                        .equals(DynamicTextCampaignSettingsGetEnum.fromValue(option.value())))
                .map(setting -> setting.getValue()).collect(Collectors.toList());
        assertThat("вернулся ожидаемый параметр", value, equalTo(Arrays.asList(settingValue)));
    }

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

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

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