package ru.yandex.autotests.direct.api.campaigns.archive;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
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.campaigns.CampaignsFeatures;
import ru.yandex.autotests.direct.api.campaigns.CampaignsLogins;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsArchived;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsStatusbssynced;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsStatusshow;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampaignsRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.darkside.datacontainers.jsonrpc.fake.BannerFakeInfo;
import ru.yandex.autotests.directapi.darkside.datacontainers.jsonrpc.fake.GroupFakeInfo;
import ru.yandex.autotests.directapi.darkside.model.Status;
import ru.yandex.autotests.directapi.model.User;
import ru.yandex.autotests.directapi.model.common.Value;
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.hazelcast.SemaphoreRule;

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

/**
 * Created by gerdler on 21.09.18.
 */
@Aqua.Test
@Features(CampaignsFeatures.ARCHIVE)
@Description("Проверка статусов в БД при архивации медийной кампании")
public class ArchiveCpmBannerCampaignsDBStatusTest {

    private static LogSteps log = LogSteps.getLogger(ArchiveCpmBannerCampaignsDBStatusTest.class);
    private static final String client = CampaignsLogins.SINGLE_CLIENT_ARCHIVE;

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

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

    private static Long groupID;
    private static CampaignsRecord campaignDB;
    private static BannerFakeInfo adInfo;
    private static final DateTime lastChange = DateTime.now().minusDays(5);

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

    @BeforeClass
    @Description("Подготовим данные для теста")
    public static void initTest() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        Long campaignID = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign();
        groupID = api.userSteps.adGroupsSteps().addDefaultCpmBannerKeywordsAdGroup(campaignID);
        DirectJooqDbSteps dbSteps =  api.userSteps.getDarkSideSteps().getDirectJooqDbSteps().useShardForLogin(client);
        Long creativeId = dbSteps.perfCreativesSteps().saveDefaultCanvasCreativesForClient(
                Long.parseLong(User.get(client).getClientID()));
        Long adID = api.userSteps.adsSteps().addDefaultCpmBannerAdBuilderAd(groupID, creativeId);
        api.userSteps.campaignSteps().campaignsSuspend(campaignID);

        log.info("Выставим статусы синхронизации с БК фейково");
        api.userSteps.campaignFakeSteps().setBSSynced(campaignID, true);
        api.userSteps.groupFakeSteps().setGroupFakeStatusBsSynced(groupID, Status.YES);
        api.userSteps.bannersFakeSteps().setStatusBsSynced(adID, Status.YES);

        log.info("Сдвинем время последнего изменения на несколько дней");
        api.userSteps.campaignFakeSteps().setLastChange(campaignID, lastChange.toString());
        api.userSteps.groupFakeSteps().setLastChange(groupID, lastChange.toString());
        api.userSteps.bannersFakeSteps().setLastChange(adID, lastChange.toString());

        log.info("Заархивируем кампанию");
        api.userSteps.campaignSteps().campaignsArchive(campaignID);
        int shard = api.userSteps.clientFakeSteps().getUserShard(client);
        campaignDB = api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps().getCampaignById(campaignID);
        adInfo = api.userSteps.bannersFakeSteps().getBannerParams(adID);
    }

    @Test
    public void campaignStatusArchivedTest() {
        assertThat("поле Archived после архивации медийной кампании", campaignDB.getArchived(),
                equalTo(CampaignsArchived.Yes));
    }

    @Test
    public void campaignStatusShowTest() {
        assertThat("поле StatusShow после архивации медийной кампании", campaignDB.getStatusshow(),
                equalTo(CampaignsStatusshow.No));
    }

    @Test
    public void campaignBsSyncedTest() {
        assertThat("поле StatusBsSynced после архивации медийной кампании", campaignDB.getStatusbssynced(),
                equalTo(CampaignsStatusbssynced.No));
    }

    @Test
    public void campaignLastChangeTest() {
        LocalDate date = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.0")
                .parseLocalDate(campaignDB.getLastchange().toString());

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

    @Test
    public void groupStatusShowsForecastTest() {
        GroupFakeInfo group = api.userSteps.groupFakeSteps().getGroupParams(groupID);

        assertThat("поле StatusShowsForecast после архивации медийной кампании", group.getStatusShowsForecast(),
                equalTo("Archived"));
    }

    @Test
    public void groupStatusBsSyncedTest() {
        GroupFakeInfo group = api.userSteps.groupFakeSteps().getGroupParams(groupID);

        assertThat("поле StatusBsSynced после архивации медийной кампании", group.getStatusBsSynced(),
                equalTo(Value.YES));
    }

    @Test
    public void adStatusBsSyncedTest() {
        assertThat("поле StatusBsSynced после архивации медийной кампании", adInfo.getStatusBsSynced(),
                equalTo(Value.YES));
    }

    @Test
    public void adStatusActiveTest() {
        assertThat("поле StatusActive после архивации медийной кампании", adInfo.getStatusActive(), equalTo(Value.NO));
    }

    @Test
    public void adLastChangeTest() {
        LocalDate date = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseLocalDate(adInfo.getLastChange());

        assertThat("время последнего изменения объявления после архивации медийной кампании", date,
                equalTo(LocalDate.now()));
    }
}
