package ru.yandex.autotests.directintapi.bstransport.main.banner.parameters.mobile;

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

import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
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.tables.records.DomainsRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.MobileContentRecord;
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.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.model.User;
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.MobileContentCleanupRule;
import ru.yandex.autotests.directintapi.bstransport.StoriesNames;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.allure.annotations.Issues;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directapi.darkside.model.MobileContentUtils.getDefaultMobileContent;
import static ru.yandex.autotests.directapi.model.User.get;
import static ru.yandex.autotests.directintapi.bstransport.TransportTestUtils.getDefaultAdgroupsMobileContent;
import static ru.yandex.autotests.directintapi.bstransport.TransportTestUtils.getDefaultBannersMobileContent;
import static ru.yandex.autotests.directintapi.bstransport.TransportTestUtils.getDefaultCampaignsMobileContent;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by buhter on 12/08/15.
 * https://st.yandex-team.ru/TESTIRT-6659
 */
@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Issues({@Issue("https://st.yandex-team.ru/DIRECT-42673"),
        @Issue("https://st.yandex-team.ru/DIRECT-68689")})
@Title("Транспорт: баннеры с типом mobile_content, поля SiteFilter, DomainFilter")
@Stories(StoriesNames.BANNER_PARAMS_MOBILE_CONTENT)
@Features(FeatureNames.BANNERS)
@RunWith(Parameterized.class)
public class BsTransportOfMobileBannerFiltersTest {

    private static final Long YANDEX_DOMAIN_ID = 29170L;
    private static final String YANDEX_DOMAIN_FILTER = "www.yandex.ru";
    private static final String TEST_BUNDLE = "ru.yandex.autotests.bundle";
    private static final Long MOMONDO_COM_DOMAIN_ID = 915343L;
    private static final String MOMONDO_DOMAIN_FILTER = "momondo.ru";
    private static final String MOMONDO_BUNDLE = "com.momondo.flightsearch";
    private static final Long IP_DOMAIN_ID = 9018215L;
    private static final String IP_DOMAIN = "193.124.186.230";
    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final String STORE_PREFIX = "ITunes_";
    private static final Long VK_COM_DOMAIN_ID = 219099L;
    private static final String VK_DOMAIN_FILTER = "vk.com";
    private static final Long M_VK_COM_DOMAIN_ID = 1392351L;
    private static final String VK_BUNDLE = "com.vkontakte.android";
    private static final String GLUED_BUNDLE = "ru.bundle.glued";

    @ClassRule
    public static final ApiSteps api = new ApiSteps().as(LOGIN);
    @ClassRule
    public static final SemaphoreRule semaphore = Semaphore.getSemaphore();
    @Rule
    public Trashman trasher = new Trashman(api);
    @Rule
    public MobileContentCleanupRule cleanupRule = new MobileContentCleanupRule(api);

    private Banner banner;

    @Parameterized.Parameter()
    public String bundle;

    @Parameterized.Parameter(1)
    public Long domainId;

    @Parameterized.Parameter(2)
    public String expectedSiteFilter;

    @Parameterized.Parameter(3)
    public String expectedDomainFilter;

    @Parameterized.Parameters(name = "bundle = {0}, domain_id = {1}")
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][]{
                {
                        TEST_BUNDLE,
                        YANDEX_DOMAIN_ID,
                        TEST_BUNDLE,
                        YANDEX_DOMAIN_FILTER
                },
                {
                        TEST_BUNDLE,
                        null,
                        TEST_BUNDLE,
                        TEST_BUNDLE
                },
                {
                        MOMONDO_BUNDLE,
                        MOMONDO_COM_DOMAIN_ID,
                        MOMONDO_BUNDLE,
                        MOMONDO_DOMAIN_FILTER
                },
                {
                        null,
                        YANDEX_DOMAIN_ID,
                        "",
                        YANDEX_DOMAIN_FILTER
                },
                {
                        null,
                        null,
                        "",
                        User.get(LOGIN).getClientID() + ".mobapp"
                },
                {
                        null,
                        IP_DOMAIN_ID,
                        "",
                        User.get(LOGIN).getClientID() + ".mobapp"
                },
                {
                        VK_BUNDLE,
                        VK_COM_DOMAIN_ID,
                        VK_BUNDLE,
                        VK_DOMAIN_FILTER
                },
                {
                        VK_BUNDLE,
                        M_VK_COM_DOMAIN_ID,
                        VK_BUNDLE,
                        VK_DOMAIN_FILTER
                },
                {
                        GLUED_BUNDLE,
                        VK_COM_DOMAIN_ID,
                        GLUED_BUNDLE,
                        STORE_PREFIX.toLowerCase() + GLUED_BUNDLE,
                },
                {
                        GLUED_BUNDLE,
                        M_VK_COM_DOMAIN_ID,
                        GLUED_BUNDLE,
                        STORE_PREFIX.toLowerCase() + GLUED_BUNDLE,
                }
        };
        return Arrays.asList(data);
    }

    @Before
    @Step("Подготовка данных")
    public void beforeClass() {
        int shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);

        // готовим домен
        DomainsRecord record = api.userSteps.getDirectJooqDbSteps().useShard(shard).domainsSteps().getDomain(IP_DOMAIN);
        if (record == null) {
            api.userSteps.getDirectJooqDbSteps().useShard(shard).domainsSteps().createDomain(IP_DOMAIN_ID, IP_DOMAIN);
        }

        MobileContentRecord sendingMobileContent
                = getDefaultMobileContent(get(LOGIN).getClientID());
        sendingMobileContent.setBundleId(bundle);
        sendingMobileContent.setPublisherDomainId(domainId);
        Long mobileContentId = api.userSteps.getDirectJooqDbSteps().useShard(shard)
                .mobileContentSteps().saveMobileContent(sendingMobileContent);

        Long cid = api.userSteps.campaignSteps().addDefaultMobileAppCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultMobileGroup(cid);
        Long bid = api.userSteps.adsSteps().addDefaultMobileAppAd(pid);
        long 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);

        cleanupRule.setMobileContentIds(singletonList(mobileContentId));
        cleanupRule.setPids(singletonList(pid));
        cleanupRule.setShard(shard);

        api.userSteps.getDirectJooqDbSteps().useShard(shard).mobileContentSteps()
                .updateCampaignsMobileContent(getDefaultCampaignsMobileContent(cid));
        api.userSteps.getDirectJooqDbSteps().useShard(shard).mobileContentSteps()
                .updateAdgroupsMobileContent(getDefaultAdgroupsMobileContent(pid, mobileContentId));
        api.userSteps.getDirectJooqDbSteps().useShard(shard).mobileContentSteps()
                .updateBannersMobileContent(getDefaultBannersMobileContent(bid));

        RunBsTransportScriptResponse resp =
                api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Campaign campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, cid);
        assumeThat("кампания отправляется в БК", campaign, notNullValue());

        Context context = campaign.getContext(pid);
        assumeThat("в кампании присутствует Context", context, notNullValue());

        banner = context.getBanner(bid);

        assumeThat("в контексте присутствует Banner", banner, notNullValue());

    }

    @Test
    public void testTransportOfBannerMobileContentAction() {
        assertThat("при отправке баннера с типом mobile_content отправляется правильное значение DomainFilter",
                banner.getDomainFilter(), equalTo(expectedDomainFilter));
        assertThat("при отправке баннера с типом mobile_content отправляется правильное значение SiteFilter",
                banner.getSiteFilter(), equalTo(expectedSiteFilter));
    }
}

