package ru.yandex.autotests.directintapi.bstransport.main.fulllbexport;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Before;
import org.junit.ClassRule;
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.db.models.jooq.ppc.enums.BannersStatusbssynced;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsStatusbssynced;
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.CampaignsRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.PhrasesRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
import ru.yandex.autotests.directapi.darkside.model.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.bslogs.UpdateInfo;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Banner;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Context;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Phrase;
import ru.yandex.autotests.directapi.darkside.steps.ScriptParamsProfiles;
import ru.yandex.autotests.directapi.darkside.tags.TestDomains;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.StoriesNames;
import ru.yandex.autotests.directintapi.bstransport.TransportHelpSteps;
import ru.yandex.autotests.irt.testutils.beandiffer2.comparestrategy.defaultcomparestrategy.DefaultCompareStrategies;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static junit.framework.TestCase.assertEquals;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.IsNull.notNullValue;
import static ru.yandex.autotests.directapi.darkside.steps.TransportSteps.getBsClientDataBanner;
import static ru.yandex.autotests.directapi.darkside.steps.TransportSteps.getBsClientDataContext;
import static ru.yandex.autotests.directapi.darkside.steps.TransportSteps.getBsClientDataPhrase;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Tag(TestDomains.BsTransport.EXPORT_QUEUE)
@Title("Проверка отправки объектов в новой кампании при полном экспорте в LogBroker")
@Stories(StoriesNames.FULL_LB_SEND)
@Features({FeatureNames.FULL_EXPORT, FeatureNames.NOT_FOR_FULL_EXPORT})
@RunWith(Parameterized.class)
public class SendNewCampaignTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

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

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

    @Parameterized.Parameter()
    public Boolean campaignInQueue;

    @Parameterized.Parameters(name = "добавление кампании в очередь: {0}")
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][]{
                {Boolean.FALSE},
                {Boolean.TRUE}
        };
        return Arrays.asList(data);
    }

    private DirectJooqDbSteps jooqDbSteps;

    private int shard;
    private Long cid;
    private Long pid;
    private Long bid;
    private long keywordId;
    private RunBsTransportScriptResponse resp;

    @Before
    public void beforeClass() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);

        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        bid = api.userSteps.adsSteps().addDefaultTextAd(pid);
        keywordId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);

        if (campaignInQueue) {
            api.userSteps.getDarkSideSteps().getTransportSteps().runBsExportMasterScript(shard, cid);
        }

        api.userSteps.getDarkSideSteps().getBsExportSteps().addCampaignToFullExportQueue(cid);
        resp = api.userSteps.transportSteps().runBsClientDataScript(shard, cid,
                ScriptParamsProfiles.ProfileNames.FULL_EXPORT);
    }

    @Test
    @Title("Проверяем отправку и статусы после отправки")
    public void test() {
        Campaign campaign = api.userSteps.transportSteps().getClientDataRequestCampaign(resp, cid);
        assumeThat("кампания отправилась", campaign, notNullValue());
        CampaignsRecord actualCampaign = jooqDbSteps.campaignsSteps().getCampaignById(cid);
        assertEquals("у кампании правильный статус", actualCampaign.getStatusbssynced(),
                campaignInQueue ? CampaignsStatusbssynced.Sending : CampaignsStatusbssynced.No);
        assertEquals("OrderID корректный", actualCampaign.getOrderid(), Long.valueOf(0));

        Context context = getBsClientDataContext(campaign, pid);
        assumeThat("группа отправилась", context, notNullValue());
        PhrasesRecord actualPhrase = jooqDbSteps.adGroupsSteps().getPhrases(pid);
        assertEquals("у группы правильный статус", actualPhrase.getStatusbssynced(),
                campaignInQueue ? PhrasesStatusbssynced.Sending : PhrasesStatusbssynced.No);

        Banner banner = getBsClientDataBanner(campaign, pid, bid);
        assumeThat("баннер отправился", banner, notNullValue());
        BannersRecord actualBanner = jooqDbSteps.bannersSteps().getBanner(bid);
        assertEquals("у баннера правильный статус", actualBanner.getStatusbssynced(),
                campaignInQueue ? BannersStatusbssynced.Sending : BannersStatusbssynced.No);

        Phrase phrase = getBsClientDataPhrase(campaign, pid, keywordId);
        assumeThat("фраза отправилась", phrase, notNullValue());

        if (!campaignInQueue) {
            RunBsTransportScriptResponse response = api.userSteps.transportSteps().runBsClientDataScript(shard, cid);
            assertThat("при попытке отправки в БК ничего не отправилось", response, nullValue());
        }
    }
}
