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

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.cmd.rules.DirectCmdRule;
import ru.yandex.autotests.direct.cmd.rules.PerformanceBannersRule;
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.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.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.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
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;

@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Features(FeatureNames.SMART_BANNERS)
@Issues({@Issue("https://st.yandex-team.ru/DIRECT-100514"),
        @Issue("https://st.yandex-team.ru/DIRECT-153698")})
@Title("Отправка в БК полей TargetDomain, TargetDomainID, Site фида")
@RunWith(Parameterized.class)
public class BsTransportOfPerformanceTargetDomainTest {

    @ClassRule
    public static final SemaphoreRule semaphore = Semaphore.getSemaphore();
    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    @ClassRule
    public static final ApiSteps api = new ApiSteps().as(LOGIN);
    private static PerformanceBannersRule bannersRule = new PerformanceBannersRule().withUlogin(LOGIN);
    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
    public String targetDomain;
    @Parameterized.Parameter(1)
    public String bsTargetDomain;
    @Parameterized.Parameter(2)
    public String bsSite;
    private TransportHelpSteps helpSteps = new TransportHelpSteps(api);
    private Banner banner;

    @Parameterized.Parameters(name = "Feed TargetDomain = {0}, BS TargetDomain = {1}, BS Site = {2}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                        {"", "", ""},
                        {null, "", ""},
                        {"legitaircompany.travel", "legitaircompany.travel", "legitaircompany.travel"},
                        {"xn--g1aelco7ds.xn--p1ai", "xn--g1aelco7ds.xn--p1ai", "союзный.рф"},
                        {"arkhyz.spb.ru", "arkhyz.spb.ru", "arkhyz.spb.ru"},
                        {"market.yandex.ru", "market.yandex.ru", "market.yandex.ru"},
                        {"watsons.com.ru", "watsons.com.ru", "watsons.com.ru"},
                        {"www.watsons.com.ru", "watsons.com.ru", "watsons.com.ru"},
                        {"tolyatti.leroymerlin.ru", "leroymerlin.ru", "leroymerlin.ru"},
                        // если перестанет проходить, то уже не зеркало. Нужно найти другое зеркало в ppcdict.mirrors
                        {"www.4glaza.ru", "levenhuk-opt.ru", "4glaza.ru"}
                }
        );
    }

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

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

        api.userSteps.getDirectJooqDbSteps().useShard(shard).feedsSteps().updateFeed(
                api.userSteps.getDirectJooqDbSteps().useShard(shard).feedsSteps().getFeed(bannersRule.getFeedId())
                        .setTargetDomain(targetDomain)
        );

        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 performanceFeedTargetDomain() {
        assumeThat("в БК отпралено поле BannerLandData", banner.getBannerLandData(), notNullValue());
        assertThat("в БК на уровне BANNER отправилось правильное поле TargetDomain"
                , banner.getTargetDomain()
                , equalTo(bsTargetDomain));
    }

    @Test
    public void performanceFeedTargetDomainId() {
        if (targetDomain == null || targetDomain == "") {
            assertThat("в БК на уровне BANNER отправилось нулевое поле TargetDomainID"
                    , banner.getTargetDomainID()
                    , equalTo(0));
        } else {
            assertThat("в БК на уровне BANNER отправилось правильное поле TargetDomainID"
                    , banner.getTargetDomainID()
                    , allOf(greaterThan(0), lessThan(Integer.MAX_VALUE)));
        }
    }

    @Test
    public void performanceFeedSite() {
        assertThat("в БК на уровне BANNER отправилось правильное поле Site"
                , banner.getSite()
                , equalTo(bsSite));
    }
}
