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.autotests.direct.cmd.rules.DirectCmdRule;
import ru.yandex.autotests.direct.cmd.rules.PerformanceBannersRule;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.GroupParamsRecord;
import ru.yandex.autotests.directapi.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
import ru.yandex.autotests.directapi.darkside.model.HrefMacrosDMO;
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.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.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directintapi.bstransport.TransportHelpSteps;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import java.util.List;
import java.util.Map;

import javax.util.streamex.StreamEx;

import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.isEmptyString;
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 buhter on 10.12.2015
 * https://st.yandex-team.ru/TESTIRT-7968
 * https://st.yandex-team.ru/TESTIRT-10194
 */
@RunWith(Parameterized.class)
public abstract class BsTransportOfPerformanceBannerLandDataHrefParamsMacrosTestBase {
    static final String PARAMETERIZED = "Значение в Href баннера = {0}, отправляемый макрос = {1}";
    // на сколько тестов дробим. должно совпадать собственно с числом тестов :) и каждый должен использовать свою часть
    // приходится идти на эту хитрость из-за огромного размера логов, вешающих акву
    private static final int BUCKETS_NUM = 6;

    static final Map<Integer, List<Object[]>> CASES = StreamEx.of(HrefMacrosDMO.values())
            .mapToEntry(Enum::ordinal)
            .invert()
            .mapKeys(o -> o % BUCKETS_NUM)
            .mapValues(m -> new Object[]{m.getValue(), m.getMacros()})
            .grouping();

    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;
    @Rule
    public DirectCmdRule cmdRule = DirectCmdRule.defaultRule().as(Logins.LOGIN_SUPER).withRules(bannersRule);
    @Rule
    public Trashman trashman = new Trashman(api);
    @Parameterized.Parameter(0)
    public String value;
    @Parameterized.Parameter(1)
    public String macros;
    private Banner banner;
    private String hrefParams;

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

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

        hrefParams = format("value={%s}", value);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).adGroupsSteps().saveGroupParams(
                new GroupParamsRecord()
                        .setPid(bannersRule.getGroupId())
                        .setHasPhraseidHref(1)
                        .setHrefParams(hrefParams)
        );

        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
    @Title("Отправка в БК BannerLandData для перф. баннера")
    public void testBannerLandData() {
        assumeThat("в БК отправлен баннер", banner, notNullValue());
        assumeThat("UpdateInfo отправленного баннера " + UpdateInfo.UPDATE
                , banner.getUpdateInfo(), equalTo(UpdateInfo.UPDATE.value()));
        assumeThat("отправленное поле BannerLandData не пустое", banner.getBannerLandData(), not(isEmptyString()));
        BannerLandDataPerformance bannerLandDataPerformance = new Gson().fromJson(banner.getBannerLandData()
                , BannerLandDataPerformance.class);
        assertThat("отправленное в БК поле BannerLandData.HrefParams соответствуют ожидаемому",
                bannerLandDataPerformance.getHrefParams(), equalTo(hrefParams.replace(value, macros)));
    }
}
