package ru.yandex.autotests.direct.api.campaigns.update.textcampaign.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.GetResponse;
import com.yandex.direct.api.v5.campaigns.TextCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignSettingGet;
import com.yandex.direct.api.v5.campaigns.TextCampaignSettingsEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignSettingsGetEnum;
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.direct.utils.tags.TagDictionary;
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.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSettingMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignUpdateItemMap;
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.Tag;
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.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 ginger on 26.08.15.
 * https://st.yandex-team.ru/TESTIRT-6407
 */
@Aqua.Test
@Issue("https://st.yandex-team.ru/DIRECT-34568")
@Features(CampaignsFeatures.UPDATE)
@Description("Проверка поля Settings")
@Tag(TagDictionary.TRUNK)
@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 TextCampaignSettingsEnum 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 (TextCampaignSettingsEnum settingsEnum : TextCampaignSettingsEnum.values()) {
            if (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()
                        .withTextCampaign(new TextCampaignAddItemMap()
                                .defaultTextCampaign()
                                .withSettings(new TextCampaignSettingMap()
                                        .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)
                        .withTextCampaign(new TextCampaignUpdateItemMap()
                                .withSettings(new TextCampaignSettingMap()
                                        .withOption(option)
                                        .withValue(settingValue)))));
        getResponse = api.userSteps.campaignSteps().campaignsGet(
                new GetRequestMap()
                        .withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                                .withIds(campaignID))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withTextCampaignFieldNames(TextCampaignFieldEnum.SETTINGS));
        assumeThat("вернулась 1 кампания", getResponse.getCampaigns(), hasSize(1));
        assumeThat("вернулись текстовые параметры кампании", getResponse.getCampaigns().get(0).getTextCampaign(),
                notNullValue());
        assumeThat("вернулись Settings кампании", getResponse.getCampaigns().get(0).getTextCampaign().getSettings(),
                notNullValue());

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

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

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

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

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