package ru.yandex.autotests.directintapi.bstransport.main.performance.banner;

import com.google.gson.Gson;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.cmd.rules.DirectCmdRule;
import ru.yandex.autotests.direct.cmd.rules.PerformanceBannersRule;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
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.clientdata.Banner;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.BannerLandDataPerformance;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Context;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.enums.StatusYesNo;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.TransportHelpSteps;
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.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

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

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

/**
 * Created by ppalex on 06.04.16.
 * https://st.yandex-team.ru/TESTIRT-8964
 * https://st.yandex-team.ru/TESTIRT-10194
 */

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Features(FeatureNames.SMART_BANNERS)
@Issue("https://st.yandex-team.ru/DIRECT-51288")
@Description("Проверка, что внутри BannerLandData отправилось поле RemoveUtm с правильным значением")
@RunWith(Parameterized.class)
public class BsTransportOfPerformanceBannerLandDataFeedRemoveUtmTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

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

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();
    private static PerformanceBannersRule bannersRule = new PerformanceBannersRule().withUlogin(LOGIN);
    private static TransportHelpSteps helpSteps = new TransportHelpSteps(api);
    private static int shard;
    private static DirectJooqDbSteps jooqDbSteps;
    @Rule
    public DirectCmdRule cmdRule = DirectCmdRule.defaultRule().as(Logins.LOGIN_SUPER).withRules(bannersRule);
    @Rule
    public Trashman trashman = new Trashman(api);
    @Parameterized.Parameter(0)
    public Optional<Integer> isRemoveUtmDbValue;
    @Parameterized.Parameter(1)
    public StatusYesNo removeUtmExpected;
    private Banner banner;

    @BeforeClass
    public static void beforeClass() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        jooqDbSteps = api.userSteps.getDarkSideSteps().getDirectJooqDbSteps().useShard(shard);
    }

    @Parameterized.Parameters(name = "Проверка для значения в базе feeds.is_remove_utm = \"{0}\", " +
            "ожидаем отправку RemoveUtm = \"{1}\"")
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][]{
                {Optional.empty(), StatusYesNo.NO},
                {Optional.of(0), StatusYesNo.NO},
                {Optional.of(1), StatusYesNo.YES},
                {Optional.of(2), StatusYesNo.NO},
        };
        return Arrays.asList(data);
    }

    @Before
    @Step("Подготовка тестовых данных")
    public void before() {
        helpSteps.makePerformanceCampaignReadyForSendingToBS(bannersRule, shard);

        isRemoveUtmDbValue.ifPresent(newDbValue -> {
            jooqDbSteps.feedsSteps().updateFeed(jooqDbSteps.feedsSteps().getFeed(bannersRule.getFeedId())
                    .setIsRemoveUtm(newDbValue));
        });

        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard,
                bannersRule.getCampaignId());
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0,
                bannersRule.getCampaignId());
        Context context = campaign != null ? campaign.getContext(bannersRule.getGroupId()) : null;
        banner = context != null ? context.getBanner(bannersRule.getBannerId()) : null;
        assumeThat("в БК отправлен баннер", banner, notNullValue());
    }

    @Test
    public void performanceBannerLandDataFeedRemoveUtm() {
        assumeThat("в БК на уровне BANNER отправлено поле BannerLandData", banner.getBannerLandData(), notNullValue());
        BannerLandDataPerformance bannerLandData = new Gson().fromJson(banner.getBannerLandData()
                , BannerLandDataPerformance.class);
        assumeThat("BannerLandData содержит поле RemoveUtm", bannerLandData.getRemoveUtm(), notNullValue());
        assertThat("отправленное в БК значение BannerLandData.RemoveUtm соответствуют ожидаемому"
                , bannerLandData.getRemoveUtm()
                , equalTo(removeUtmExpected));
    }
}
