package ru.yandex.autotests.direct.api.ads.suspend;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;

import org.junit.Before;
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.api.ads.AdsFeatures;
import ru.yandex.autotests.direct.api.ads.AdsLogins;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersMinusGeoType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersStatusbssynced;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampOptionsStatusmetricacontrol;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PhrasesStatusautobudgetshow;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PhrasesStatusbssynced;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BannersRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampOptionsRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.PhrasesRecord;
import ru.yandex.autotests.direct.db.steps.AdGroupsSteps;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.enums.AdGroupType;
import ru.yandex.autotests.directapi.enums.BannerType;
import ru.yandex.autotests.directapi.enums.CampaignType;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.IdsCriteriaMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
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.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by pavryabov on 16.04.15.
 * https://st.yandex-team.ru/TESTIRT-4842
 */
@Aqua.Test
@Features(AdsFeatures.SUSPEND)
@Description("Проверка влияния Suspend на статусы баннера")
@Issue("https://st.yandex-team.ru/DIRECT-34573")
@Tag(TagDictionary.TRUNK)
@RunWith(Parameterized.class)
public class CheckFakeStatusesAfterSuspendTest {

    private static final String LOGIN = AdsLogins.CLIENT;

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

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

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

    Long campaignId;
    Long adGroupId;
    Long adId;

    @Parameterized.Parameter(0)
    public CampaignType campaignType;

    @Parameterized.Parameter(1)
    public AdGroupType adGroupType;

    @Parameterized.Parameter(2)
    public BannerType bannerType;

    @Parameterized.Parameters(name = "bannerType = {2}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {CampaignType.TEXT, AdGroupType.BASE, BannerType.TEXT},
                {CampaignType.MOBILE_CONTENT, AdGroupType.MOBILE_CONTENT, BannerType.MOBILE_CONTENT},
                {CampaignType.DYNAMIC, AdGroupType.DYNAMIC, BannerType.DYNAMIC},
        });
    }

    @BeforeClass
    public static void initTest() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(AdsLogins.CLIENT);
    }

    @Before
    public void createObjects() {
        int shard = api.userSteps.clientFakeSteps().getUserShard(AdsLogins.CLIENT);
        campaignId = api.userSteps.campaignSteps().addDefaultCampaign(campaignType);
        CampOptionsRecord campOptions = jooqSteps(LOGIN).campaignsSteps().getCampOptionsById(campaignId);
        campOptions.setStatusmetricacontrol(CampOptionsStatusmetricacontrol.Yes);
        jooqSteps(LOGIN).campaignsSteps().updateCampOptions(campOptions);
        adGroupId = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId, adGroupType);
        adId = api.userSteps.adsSteps().addDefaultAd(adGroupId, bannerType);
        api.userSteps.bannersFakeSteps().makeBannersModerated(adId);
    }

    @Test
    public void checkStatusBsSynced() {
        jooqSteps(LOGIN).bannersSteps().updateBanners(
                new BannersRecord().setBid(adId).setStatusbssynced(BannersStatusbssynced.Yes));
        BannersStatusbssynced statusBefore = jooqSteps(LOGIN).bannersSteps().getBanner(adId).getStatusbssynced();
        assumeThat("StatusBsSynced = Yes", statusBefore, equalTo(BannersStatusbssynced.Yes));
        api.userSteps.adsSteps()
                .shouldGetResultOnSuspend(new IdsCriteriaMap().withIds(adId), ExpectedResult.success(adId));
        BannersStatusbssynced statusAfter = jooqSteps(LOGIN).bannersSteps().getBanner(adId).getStatusbssynced();
        assertThat("StatusBsSynced = No", statusAfter, equalTo(BannersStatusbssynced.No));
    }

    @Test
    public void checkLastChangeOfBanner() {
        Timestamp lastChange = Timestamp.valueOf(LocalDateTime.now().minusHours(1).truncatedTo(ChronoUnit.SECONDS));
        jooqSteps(LOGIN).bannersSteps().setBannersLastChange(adId, lastChange);
        Timestamp lastChangeBefore = jooqSteps(LOGIN).bannersSteps().getBanner(adId).getLastchange();
        assumeThat("lastChange = " + lastChange, lastChangeBefore, equalTo(lastChange));
        api.userSteps.adsSteps()
                .shouldGetResultOnSuspend(new IdsCriteriaMap().withIds(adId), ExpectedResult.success(adId));
        Timestamp lastChangeAfter = jooqSteps(LOGIN).bannersSteps().getBanner(adId).getLastchange();
        assertThat("lastChange изменился", lastChangeAfter, not(equalTo(lastChange)));
    }

    @Test
    public void checkStatusAutobudgetShow() {
        //DIRECT-41201
        jooqSteps(LOGIN).adGroupsSteps().updatePhrases(
                new PhrasesRecord().setPid(adGroupId).setStatusautobudgetshow(PhrasesStatusautobudgetshow.No));
        PhrasesStatusautobudgetshow statusBefore = jooqSteps(LOGIN)
                .adGroupsSteps().getPhrases(adGroupId).getStatusautobudgetshow();
        assumeThat("StatusAutobudgetShow = No", statusBefore, equalTo(PhrasesStatusautobudgetshow.No));
        api.userSteps.adsSteps()
                .shouldGetResultOnSuspend(new IdsCriteriaMap().withIds(adId), ExpectedResult.success(adId));
        PhrasesStatusautobudgetshow statusAfter = jooqSteps(LOGIN)
                .adGroupsSteps().getPhrases(adGroupId).getStatusautobudgetshow();
        assertThat("StatusAutobudgetShow = Yes", statusAfter, equalTo(PhrasesStatusautobudgetshow.Yes));
    }
    
    @Test
    public void adsSuspend_BannerDoesNotAffectAdGroupTargeting_AdGroupStatusNotChanged() {
        final PhrasesStatusbssynced statusBefore = PhrasesStatusbssynced.Yes;
        jooqSteps(LOGIN).adGroupsSteps().setPhrasesStatusBsSynced(adGroupId, statusBefore);
        jooqSteps(LOGIN).bannersSteps().updateBanners(jooqSteps(LOGIN).bannersSteps().getBanner(adId).setBannerid(1L));
        api.userSteps.adsSteps()
                .shouldGetResultOnSuspend(new IdsCriteriaMap().withIds(adId), ExpectedResult.success(adId));
        PhrasesStatusbssynced statusAfter = jooqSteps(LOGIN).adGroupsSteps().getPhrases(adGroupId).getStatusbssynced();
        assertThat("Флаг отправки в БК группы не изменился", statusAfter, equalTo(statusBefore));
    }

    @Test
    public void adsSuspend_BannerAffectsAdGroupTargeting_AdGroupStatusChanged() {
        final PhrasesStatusbssynced statusBefore = PhrasesStatusbssynced.Yes;
        final PhrasesStatusbssynced expected = PhrasesStatusbssynced.No;
        final AdGroupsSteps adGroupsSteps = jooqSteps(LOGIN).adGroupsSteps();

        PhrasesRecord phrasesRecord = adGroupsSteps.getPhrases(adGroupId);
        phrasesRecord.setGeo("1").setStatusbssynced(statusBefore);
        adGroupsSteps.updatePhrases(phrasesRecord);

        jooqSteps(LOGIN).bannersSteps().saveBannersMinusGeo(adId, BannersMinusGeoType.current, "1");
        jooqSteps(LOGIN).bannersSteps().updateBanners(jooqSteps(LOGIN).bannersSteps().getBanner(adId).setBannerid(1L));

        api.userSteps.adsSteps()
                .shouldGetResultOnSuspend(new IdsCriteriaMap().withIds(adId), ExpectedResult.success(adId));
        PhrasesStatusbssynced statusAfter = adGroupsSteps.getPhrases(adGroupId).getStatusbssynced();
        assertThat("Флаг отправки в БК группы изменился", statusAfter, equalTo(expected));
    }

    @Test
    public void adsSuspend_BannerNeverSentToBs_AdGroupStatusNotChanged() {
        final PhrasesStatusbssynced statusBefore = PhrasesStatusbssynced.Yes;
        jooqSteps(LOGIN).adGroupsSteps().setPhrasesStatusBsSynced(adGroupId, statusBefore);
        jooqSteps(LOGIN).bannersSteps().updateBanners(jooqSteps(LOGIN).bannersSteps().getBanner(adId).setBannerid(0L));
        api.userSteps.adsSteps()
                .shouldGetResultOnSuspend(new IdsCriteriaMap().withIds(adId), ExpectedResult.success(adId));
        PhrasesStatusbssynced statusAfter = jooqSteps(LOGIN).adGroupsSteps().getPhrases(adGroupId).getStatusbssynced();
        assertThat("Флаг отправки в БК группы не изменился", statusAfter, equalTo(statusBefore));
    }

    private DirectJooqDbSteps jooqSteps(String login) {
        return api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN);
    }
}
