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

import org.apache.commons.lang.RandomStringUtils;
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.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.Campaign;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Context;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
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.ArrayList;
import java.util.Collection;
import java.util.List;

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 pashkus on 05.04.16.
 * https://st.yandex-team.ru/TESTIRT-8695
 * https://st.yandex-team.ru/TESTIRT-10194
 */
@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Issue("https://st.yandex-team.ru/DIRECT-51468")
@Description("Транспорт: отправка в БК поля Resources.ClickUrlTail на уровне CONTEXT;" +
        "проверяем подстановку макросов")
@Features(FeatureNames.SMART_BANNERS)
@RunWith(Parameterized.class)
public class BsTransportOfPerformanceClickUrlTailMacrosTest {
    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 userDefinedClickUrlTail;
    @Parameterized.Parameter(1)
    public String expectedClickUrlTail;
    private Context context;

    @Parameterized.Parameters(name = "Ожидаем что для указанный пользователем хвостик {0}, заменяется транспортом на {1}")
    public static Collection data() {
        List<String> actualParamValues = new ArrayList<>();
        List<String> expectedParamValues = new ArrayList<>();

        for (HrefMacrosDMO hrefMacros : HrefMacrosDMO.values()) {
            String userUrlParam = "userParam" + RandomStringUtils.randomNumeric(2).toString();
            actualParamValues.add(format(userUrlParam + "={%s}", hrefMacros.getValue()));
            expectedParamValues.add(format(userUrlParam + "={%s}", hrefMacros.getMacros()));
        }

        List<Object[]> data = new ArrayList<Object[]>();
        //строка содержащая все допустимые параметры
        data.add(new Object[]{new String().join("&", actualParamValues),
                new String().join("&", expectedParamValues)});
        //строка содержит один параметр
        data.add(new Object[]{new String().join("&", actualParamValues.get(0)),
                new String().join("&", expectedParamValues.get(0))});
        //строка содержит неск. одинаковых параметров
        data.add(new Object[]{new String().join("&", actualParamValues.get(0),
                actualParamValues.get(1),
                actualParamValues.get(1)),
                new String().join("&", expectedParamValues.get(0),
                        expectedParamValues.get(1),
                        expectedParamValues.get(1))});
        return data;
    }

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

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

        api.userSteps.getDirectJooqDbSteps().useShard(shard).adGroupsSteps().saveGroupParams(
                new GroupParamsRecord()
                        .setHrefParams(userDefinedClickUrlTail)
                        .setHasPhraseidHref(1)
                        .setPid(bannersRule.getGroupId())
        );
        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard,
                bannersRule.getCampaignId());
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0,
                bannersRule.getCampaignId());
        context = campaign != null ? campaign.getContext(bannersRule.getGroupId()) : null;
        assumeThat("в БК отправлен CONTEXT", context, notNullValue());
    }

    @Test
    @Description("Проверяем, что ClickUrlTail отправляется на уровне CONTEXT")
    public void testClickUrlTailInContext() {
        assumeThat("UpdateInfo отправленного контекста " + UpdateInfo.UPDATE,
                context.getUpdateInfo(), equalTo(UpdateInfo.UPDATE.value()));
        assumeThat("поле CONTEXT.Resource.ClickUrlTail не пустое", context.getResources().getClickUrlTail(),
                not(isEmptyString()));
        assertThat("отправленное в БК поле Resource.ClickUrlTail соответсвует ожиданиям",
                context.getResources().getClickUrlTail(), equalTo(expectedClickUrlTail));
    }
}
