package ru.yandex.autotests.directintapi.bstransport.main.dynimage.parameters.bannerland;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannerImagesStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.DynamicConditionsRecord;
import ru.yandex.autotests.direct.utils.model.RegionIDValues;
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.datacontainers.jsonrpc.dynamicadgroups.ConditionData;
import ru.yandex.autotests.directapi.darkside.datacontainers.jsonrpc.dynamicadgroups.TargetDataDynamic;
import ru.yandex.autotests.directapi.darkside.model.ImageType;
import ru.yandex.autotests.directapi.darkside.model.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.Status;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Banner;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.BannerLandDataDynamic;
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.api5.adgroups.AdGroupAddItemMap;
import ru.yandex.autotests.directapi.model.api5.adgroups.DynamicTextAdGroupMap;
import ru.yandex.autotests.directapi.model.api5.ads.AdUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.DynamicTextAdUpdateMap;
import ru.yandex.autotests.directapi.model.api5.ads.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.StoriesNames;
import ru.yandex.autotests.directintapi.bstransport.TransportHelpSteps;
import ru.yandex.autotests.directintapi.bstransport.TransportTestUtils;
import ru.yandex.autotests.irt.testutils.json.JsonUtils;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.empty;
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;
import static ru.yandex.autotests.irt.testutils.beandiffer.BeanDifferMatcher.beanEquivalent;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: проверка отправки в БК BannerLandData для картинки дин. баннера")
@Stories(StoriesNames.DYN_IMAGE_PARAMS_BANNERLAND)
@Features(FeatureNames.DYN_IMAGES)
public class BsTransportOfBannerLandWithImageTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final String RAND_DOMAIN = TransportTestUtils.randomDomain();

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(LOGIN);

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();

    private static TransportHelpSteps helpSteps = new TransportHelpSteps(api);

    private int shard;
    private Long pid;
    private Context context;
    private Banner pic;

    @Before
    public void beforeClass() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        String[] imageHashes = helpSteps.addImagesForUserIfNotExists(LOGIN, ImageType.REGULAR);

        Long cid = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        pid = api.userSteps.adGroupsSteps().addGroup(new AdGroupAddItemMap()
                .defaultAdGroupAddItem(cid)
                .withRegionIds(RegionIDValues.MOSCOW_AND_MOSCOW_REGION.getId().longValue())
                .withDynamicTextAdGroup(new DynamicTextAdGroupMap()
                        .withDomainUrl(RAND_DOMAIN)));
        api.userSteps.dynamicTextAdTargetsSteps().addDefaultWebpage(pid);
        Long picBid = api.userSteps.adsSteps().addDefaultDynamicTextAd(pid);

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(picBid);

        api.userSteps.adsSteps().shouldGetResultOnUpdate(new UpdateRequestMap().withAds(new AdUpdateItemMap()
                        .withId(picBid)
                        .withDynamicTextAd(new DynamicTextAdUpdateMap().withAdImageHash(imageHashes[0]))),
                ExpectedResult.success());
        Long imageId = api.userSteps.getDirectJooqDbSteps().useShard(shard).
                imagesSteps().getBannerImagesByBid(picBid).getImageId();
        api.userSteps.getDirectJooqDbSteps().useShard(shard).imagesSteps()
                .setBannerImagesStatusModerate(imageId, BannerImagesStatusmoderate.Yes);

        api.userSteps.groupFakeSteps().setGroupFakeStatusBsSynced(pid, Status.NO);
        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
        context = campaign != null ? campaign.getContext(pid) : null;
        pic = context != null ? context.getBanner(imageId) : null;
    }

    @Test
    @Title("Отправка в БК BannerLandData для картинки дин. баннера")
    public void testBannerLandData() {

        assumeThat("в БК отправлен картиночный баннер", pic, notNullValue());
        assumeThat("отправленное поле BannerLandData не пустое", pic.getBannerLandData(), not(isEmptyString()));
        String bannerLand = pic.getBannerLandData().replaceAll("\\\\", "");
        BannerLandDataDynamic bannerLandDataDynamic = JsonUtils.getObject(bannerLand, BannerLandDataDynamic.class);

        BannerLandDataDynamic expected = new BannerLandDataDynamic();
        List<DynamicConditionsRecord> conditions = api.userSteps.getDirectJooqDbSteps().useShard(shard)
                .dynamicConditionsSteps()
                .getDynamicConditionsByAdgroupId(pid);
        assumeThat("список полученных из базы условий нацеливания не пустой"
                , conditions
                , not(empty()));

        TargetDataDynamic targetData = new TargetDataDynamic();
        targetData.setDynamicConditionId(conditions.get(0).getDynCondId());
        targetData.setCondition(
                Arrays.asList(JsonUtils.getObject(conditions.get(0).getConditionJson(), ConditionData[].class)));

        List<TargetDataDynamic> targetDataList = new ArrayList<>();
        targetDataList.add(targetData);

        expected.setTargets(targetDataList);
        expected.setBody(pic.getBody());
        expected.setGeo(context != null ? context.getGeo().get(0) : null);
        expected.setCampaignMinusWords("");
        expected.setAdGroupMinusWords("");
        expected.setDomain(RAND_DOMAIN);

        assertThat("отправленное в БК поле BannerLandData.Targets соответствуют ожидаемому",
                bannerLandDataDynamic, beanEquivalent(expected));
    }
}
