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

import java.sql.Timestamp;
import java.util.List;

import org.joda.time.DateTime;
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.CampaignsStatusbssynced;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampOptionsRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampaignsRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.date.DBTimeConverter;
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.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.Tag;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by pavryabov on 19.11.15.
 */
@Aqua.Test
@Features(CampaignsFeatures.SUSPEND)
@Description("Проверка времени изменения и статусов в БД при остановке мобильной кампании")
@Tag(TagDictionary.TRUNK)
public class SuspendDynamicTextCampaignsDBStatusTest {
    private static LogSteps log = LogSteps.getLogger(SuspendDynamicTextCampaignsDBStatusTest.class);
    private static final String client = CampaignsLogins.SINGLE_CLIENT_SUSPEND;
    private static final DateTime lastChange = DateTime.now().minusMonths(1);
    private static final Timestamp lastChangeTimestamp = DBTimeConverter.jodaToSql(lastChange);

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

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

    private static CampaignFakeInfo campaignInfo;
    private static Long campaignId;
    private static CampOptionsRecord options;

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

    @BeforeClass
    public static void initTest() {


        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        campaignId = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign();

        log.info("Промодерируем фейково");
        api.userSteps.campaignFakeSteps().makeCampaignModerated(campaignId);

        final DirectJooqDbSteps jooqSteps = api.userSteps.getDirectJooqDbSteps();
        jooqSteps.useShard(api.userSteps.clientFakeSteps().getUserShard(client));

        log.info("Сдвинем время последнего изменения на несколько дней");
        final CampOptionsRecord campOptionsRecord = jooqSteps.campaignsSteps().getCampOptionsById(campaignId);
        campOptionsRecord.setStoptime(lastChangeTimestamp);
        jooqSteps.campaignsSteps().updateCampOptions(campOptionsRecord);

        log.info("Выставим статусы синхронизации с БК фейково");
        final CampaignsRecord campaignsRecord = jooqSteps.campaignsSteps().getCampaignById(campaignId);
        campaignsRecord.setStatusbssynced(CampaignsStatusbssynced.Yes);
        jooqSteps.campaignsSteps().updateCampaigns(campaignsRecord);

        log.info("Остановим кампанию");
        List<Long> ids = api.userSteps.campaignSteps().campaignsSuspend(campaignId);
        assumeThat("получили идентификатор остановленной кампании", ids, hasSize(1));
        campaignInfo = api.userSteps.campaignFakeSteps().fakeGetCampaignParams(campaignId);

        options = jooqSteps.campaignsSteps().getCampOptionsById(campaignId);
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("645")
    public void statusBsSyncedTest() {
        assertThat("статус синхронизации с БК после остановки мобильной кампании", campaignInfo.getStatusBsSynced(),
                equalTo(Value.NO));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("646")
    public void statusShowTest() {
        assertThat("поле StatusShow после остановки мобильной кампании", campaignInfo.getStatusShow(),
                equalTo(Value.NO));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("648")
    public void stopTimeTest() {
        final DateTime newStopTime = DBTimeConverter.dbTimeToJoda(options.getStoptime().toString());

        assertThat("время остановки мобильной кампании", lastChange, lessThan(newStopTime));
    }

    @Title("Bug: DIRECT-40604")
    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("647")
    public void lastChangeTest() {
        final DateTime newLastChange = DBTimeConverter
                .dbTimeToJoda(api.userSteps.campaignFakeSteps().fakeGetCampaignParams(campaignId).getLastChange());

        assertThat("время последнего изменения кампании после остановки мобильной кампании",
                lastChange, lessThan(newLastChange));
    }
}
