package ru.yandex.autotests.direct.web.data.converters;

import java.util.stream.Stream;

import org.apache.commons.collections.CollectionUtils;

import ru.yandex.autotests.direct.cmd.data.commons.banner.Banner;
import ru.yandex.autotests.direct.cmd.data.commons.group.Group;
import ru.yandex.autotests.direct.web.objects.banners.BannerPhraseInfoWeb;
import ru.yandex.autotests.direct.web.objects.banners.GroupMobileInfoWeb;
import ru.yandex.autotests.direct.web.objects.banners.MobileAppBannerInfoWeb;

import static java.lang.Long.parseLong;
import static java.util.Objects.isNull;

public class MobileBannerInfoWebConverter {
    public static MobileAppBannerInfoWeb cmdBannerToMobileAppBannerInfoWeb(Banner banner) {
        return cmdBannerToMobileAppBannerInfoWeb(banner, new MobileAppBannerInfoWeb());
    }

    public static MobileAppBannerInfoWeb cmdBannerToMobileAppBannerInfoWeb(Banner banner,
            MobileAppBannerInfoWeb resultBanner)
    {
        resultBanner.withBannerId(banner.getBid())
                .withAdGroupID(parseLong(banner.getPid()))
                .withCampaignID(banner.getCid())
                .withTitle(banner.getTitle())
                .withBody(banner.getBody())
                .withTrackingHref(banner.getHref())
                .withAdGroupName(banner.getGroupName())
                .withHashFlags(banner.getHashFlags());
        if (!isNull(resultBanner.getPhrases())) {
            Stream.of(resultBanner.getPhrases()).forEach(x -> x.setBannerId(banner.getBid()));
        }
        return resultBanner;
    }

    public static MobileAppBannerInfoWeb cmdGroupToMobileAppBannerInfoWeb(Group group,
            MobileAppBannerInfoWeb bannerInfoWeb)
    {
        GroupMobileInfoWeb groupMobileInfoWeb = new GroupMobileInfoWeb();
        groupMobileInfoWeb.withStoreContentHref(group.getStoreContentHref());
        MobileAppBannerInfoWeb result = bannerInfoWeb.withAdGroupName(group.getAdGroupName())
                .withGeo(group.getGeo())
                .withGroupMobileInfo(groupMobileInfoWeb)
                .withMinusKeywords(CollectionUtils.isEmpty(group.getMinusWords()) ?
                        null :
                        group.getMinusWords().stream().toArray(String[]::new))
                .withPhrases(CollectionUtils.isEmpty(group.getPhrases()) ?
                        null :
                        group.getPhrases().stream().map(PhraseInfoWebConverter::toInfoWebPhrase)
                                .toArray(BannerPhraseInfoWeb[]::new));
        if (result.getPhrases() != null) {
            Stream.of(result.getPhrases()).forEach(x -> {
                x.setAdGroupID(parseLong(group.getAdGroupID()));
                if (!isNull(bannerInfoWeb.getBannerId())) {
                    x.setBannerId(bannerInfoWeb.getBannerId());
                }
            });
        }
        return result;
    }
}
