package ru.yandex.autotests.direct.api.ads.update.mobileappadbuilderad;

import java.time.LocalDateTime;

import org.glassfish.gmbal.Description;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

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.BannersPerformanceStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersStatusbssynced;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BannersPerformanceRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BannersRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.darkside.model.Status;
import ru.yandex.autotests.directapi.model.User;
import ru.yandex.autotests.directapi.model.api5.ads.AdUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.MobileAppAdBuilderAdUpdateMap;
import ru.yandex.autotests.directapi.model.api5.ads.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
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.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;

/**
 * https://st.yandex-team.ru/DIRECT-71573
 */
@Aqua.Test
@Features(AdsFeatures.UPDATE)
@Description("Проверка обновления статусов (StatusBsSynced и StatusModerate) и LastChange")
@Issue("https://st.yandex-team.ru/DIRECT-58369")
public class UpdateMobileAppAdBuilderAdStatusesTest {
    private static final String CLIENT = AdsLogins.CLIENT43;
    private static Long adGroupId;
    private static Long campaignId;
    private static Long creativeId;

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

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

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

    private static Long adId;
    private static LocalDateTime previousLastChange = LocalDateTime.now().withNano(0).minusDays(1);
    private static DirectJooqDbSteps dbSteps;

    @BeforeClass
    public static void prepareData() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);
        dbSteps = api.userSteps.getDarkSideSteps().getDirectJooqDbSteps().useShardForLogin(CLIENT);
        campaignId = api.userSteps.campaignSteps().addDefaultMobileAppCampaign();
        api.userSteps.getDirectJooqDbSteps().useShardForLogin(CLIENT)
                .campaignsSteps().setCampaignsStatusModerate(campaignId, CampaignsStatusmoderate.Yes);
        adGroupId = api.userSteps.adGroupsSteps().addDefaultMobileGroup(campaignId);
        api.userSteps.keywordsSteps().addDefaultKeyword(adGroupId);
    }

    @Before
    @Step("Подготовка данных для теста")
    public void setStatuses() {
        creativeId = dbSteps.perfCreativesSteps().saveDefaultCanvasCreativesForClient(
                Long.parseLong(User.get(CLIENT).getClientID()));
        adId = api.userSteps.adsSteps().addDefaultMobileAppAdBuilderAd(adGroupId, creativeId);
        dbSteps.bannersPerformanceSteps().setCreativeStatusModerate(campaignId, adGroupId, adId, BannersPerformanceStatusmoderate.Yes);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(adId);
        api.userSteps.bannersFakeSteps().setStatusBsSynced(adId, Status.YES);
        api.userSteps.bannersFakeSteps().setLastChange(adId, previousLastChange.toString());
    }

    @Test
    public void updateUrl() {
        api.userSteps.adsSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withAds(
                        new AdUpdateItemMap().withMobileAppAdBuilderAd(
                                new MobileAppAdBuilderAdUpdateMap().withTrackingUrl("http://appmetrica.yandex.com")
                        ).withId(adId)
                ),
                ExpectedResult.success()
        );

        BannersRecord bannersRecord = dbSteps.bannersSteps().getBanner(adId);
        BannersPerformanceRecord bannersPerformance = dbSteps.bannersPerformanceSteps().getBannersPerformance(adId, creativeId);
        assertThat("в БД (banners) верное значение StatusBsSynced",
                bannersRecord.getStatusbssynced(), equalTo(BannersStatusbssynced.No));
        assertThat("в БД (banners) верное значение StatusModerate",
                bannersRecord.getStatusmoderate(), equalTo(BannersStatusmoderate.Ready));
        assertThat("в БД (banners) верное значение LastChange",
                bannersRecord.getLastchange().toLocalDateTime(), greaterThan(previousLastChange));
        assertThat("в БД (banners_performance) верное значение StatusModerate",
                bannersPerformance.getStatusmoderate(), equalTo(BannersPerformanceStatusmoderate.Ready));
    }

    @Test
    public void updateCreative() {
        Long newCreativeId = dbSteps.perfCreativesSteps().saveDefaultCanvasCreativesForClient(
            Long.parseLong(User.get(CLIENT).getClientID()));
        api.userSteps.adsSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withAds(
                        new AdUpdateItemMap().withMobileAppAdBuilderAd(
                                new MobileAppAdBuilderAdUpdateMap().withCreative(newCreativeId)
                        ).withId(adId)
                ),
                ExpectedResult.success()
        );

        BannersRecord bannersRecord = dbSteps.bannersSteps().getBanner(adId);
        BannersPerformanceRecord bannersPerformance = dbSteps.bannersPerformanceSteps().getBannersPerformance(adId, newCreativeId);
        assertThat("в БД (banners) верное значение StatusBsSynced",
                bannersRecord.getStatusbssynced(), equalTo(BannersStatusbssynced.No));
        assertThat("в БД (banners) верное значение StatusModerate",
                bannersRecord.getStatusmoderate(), equalTo(BannersStatusmoderate.Ready));
        assertThat("в БД (banners) верное значение LastChange",
                bannersRecord.getLastchange().toLocalDateTime(), greaterThan(previousLastChange));
        assertThat("в БД (banners_performance) верное значение StatusModerate",
                bannersPerformance.getStatusmoderate(), equalTo(BannersPerformanceStatusmoderate.Ready));
    }


    @Test
    public void updateWithError() {
        api.userSteps.adsSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withAds(
                        new AdUpdateItemMap().withMobileAppAdBuilderAd(
                                new MobileAppAdBuilderAdUpdateMap().withTrackingUrl("12345")
                        ).withId(adId)
                ),
                ExpectedResult.errors(
                        new Notification(5005, Api5ErrorDetails.INCORRECT_LINK)
                )
        );

        BannersRecord bannersRecord = dbSteps.bannersSteps().getBanner(adId);
        BannersPerformanceRecord bannersPerformance = dbSteps.bannersPerformanceSteps().getBannersPerformance(adId, creativeId);
        assertThat("в БД (banners) верное значение StatusBsSynced",
                bannersRecord.getStatusbssynced(), equalTo(BannersStatusbssynced.Yes));
        assertThat("в БД (banners) верное значение StatusModerate",
                bannersRecord.getStatusmoderate(), equalTo(BannersStatusmoderate.Yes));
        assertThat("в БД (banners) верное значение LastChange",
                bannersRecord.getLastchange().toLocalDateTime(), equalTo(previousLastChange));
        assertThat("в БД (banners_performance) верное значение StatusModerate",
                bannersPerformance.getStatusmoderate(), equalTo(BannersPerformanceStatusmoderate.Yes));
    }
}
