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

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

import org.junit.Before;
import org.junit.BeforeClass;
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.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.Campaign;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Context;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.ContextNetworkTargeting;
import ru.yandex.autotests.directapi.enums.NetworkTargeting;
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.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.notNullValue;
import static ru.yandex.autotests.directapi.darkside.model.MobileContentUtils.getDefaultMobileContent;
import static ru.yandex.autotests.directapi.enums.NetworkTargeting.CELL;
import static ru.yandex.autotests.directapi.enums.NetworkTargeting.WIFI;
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;
import static ru.yandex.autotests.irt.testutils.beandiffer.BeanDifferMatcher.beanDiffer;

/**
 * Created by buhter on 12/08/15.
 * https://st.yandex-team.ru/TESTIRT-6659
 */
@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Issue("https://st.yandex-team.ru/DIRECT-42673")
@Title("Транспорт: группы с типом mobile_content, поле NetworkTargeting")
@Stories(StoriesNames.GROUP_PARAMS_MOBILE)
@Features(FeatureNames.GROUPS)
@RunWith(Parameterized.class)
public class BsTransportOfMobileGroupNetworkTargetingTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

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

    private static int shard;
    private static Context context;

    @Parameterized.Parameter(0)
    public String networkTargeting;
    private ContextNetworkTargeting expected;

    @Parameterized.Parameters(name = "targeting = {0}")
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][]{
                {NetworkTargeting.CELL.toString()},
                {NetworkTargeting.WIFI.toString()},
                {NetworkTargeting.CELL.toString() + "," + NetworkTargeting.WIFI.toString()},
                {NetworkTargeting.WIFI.toString() + "," + NetworkTargeting.WIFI.toString()},
                {""}
        };
        return Arrays.asList(data);
    }


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

    @Before
    @Step("Подготовка данных")
    public void before() {
        MobileContentRecord sendingMobileContent
                = getDefaultMobileContent(get(LOGIN).getClientID());
        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).setNetworkTargeting(networkTargeting)
                );

        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 = campaign.getContext(pid);
        assumeThat("в кампании присутствует Context", context, notNullValue());
        expected = new ContextNetworkTargeting();
        if (networkTargeting.contains(CELL.toString())) {
            expected.setCell(1);
        } else {
            expected.setCell(0);
        }
        if (networkTargeting.contains(WIFI.toString())) {
            expected.setWifi(1);
        } else {
            expected.setWifi(0);
        }
    }

    @Test
    public void testTransportOfGroupMobileNetworkTargeting() {
        assertThat("при отправке группы с типом mobile_content отправляется правильное значение NetworkTargeting"
                , context.getNetworkTargeting(), beanDiffer(expected));
    }
}

