package ru.yandex.direct.web.entity.uac.converter

import ru.yandex.direct.core.entity.adgroup.container.ComplexCpmAdGroup
import ru.yandex.direct.core.entity.adgroup.model.AdGroup
import ru.yandex.direct.core.entity.adgroup.model.AdGroupType
import ru.yandex.direct.core.entity.adgroup.model.CpmBannerAdGroup
import ru.yandex.direct.core.entity.adgroup.model.CpmVideoAdGroup
import ru.yandex.direct.core.entity.adgroup.model.CriterionType
import ru.yandex.direct.core.entity.banner.model.BannerMeasurer
import ru.yandex.direct.core.entity.banner.model.BannerMeasurerSystem
import ru.yandex.direct.core.entity.banner.model.ButtonAction
import ru.yandex.direct.core.entity.banner.model.CpmBanner
import ru.yandex.direct.core.entity.uac.UacCommonUtils
import ru.yandex.direct.core.entity.uac.model.Content
import ru.yandex.direct.core.entity.uac.model.MediaType
import ru.yandex.direct.core.entity.uac.model.UacComplexBidModifier
import ru.yandex.direct.core.entity.uac.repository.ydb.UacYdbUtils.toIdLong
import ru.yandex.direct.core.entity.uac.service.UacRetargetingService
import ru.yandex.direct.web.entity.uac.model.UacModifyCampaignDataContainer

object UacGroupsConverter {
    fun toComplexCpmAdgroup(
        createDataContainer: UacModifyCampaignDataContainer,
        contents: Collection<Content>,
        clientId: Long,
    ): ComplexCpmAdGroup {
        val content: Content = contents.find { it.meta.containsKey("creative_id") }
            ?: throw java.lang.IllegalStateException("No creative id!")

        val banners = contents.filter { it.meta.containsKey("creative_id") }
            .map { toBanner(createDataContainer, it) }

        val uacComplexBidModifier = UacComplexBidModifier(
            advType = createDataContainer.advType,
            socdem = createDataContainer.socdem,
            deviceTypes = createDataContainer.deviceTypes,
            inventoryTypes = createDataContainer.inventoryTypes,
            isSmartTVEnabled = true, // enabledFeatures.contains(FeatureName.SMARTTV_BID_MODIFIER_ENABLED.name),
            isTabletModifierEnabled = true, // enabledFeatures.contains(FeatureName.TABLET_BIDMODIFER_ENABLED.name),
        )
        val complexBidModifier =
            UacCommonUtils.getComplexBidModifier(uacComplexBidModifier,createDataContainer.id.toIdLong())

        return ComplexCpmAdGroup()
            .withAdGroup(cpmAdGroup(createDataContainer, content.type))
            .withBanners(banners)
            .withComplexBidModifier(complexBidModifier)
            .withRetargetingConditions(createDataContainer.retargetingCondition?.let {
                listOf(UacRetargetingService.toCoreRetargetingCondition(it, clientId))
            })
    }

    fun toBanner(createDataContainer: UacModifyCampaignDataContainer, content: Content): CpmBanner? {
        val creativeId = (content.meta["creative_id"] as Number).toLong()
        val contentId = content.id

        val banner = CpmBanner()
            .withHref(createDataContainer.href)
            .withCreativeId(creativeId)

        if (createDataContainer.cpmAssets != null && createDataContainer.cpmAssets.containsKey(contentId)) {
            val currentAsset = createDataContainer.cpmAssets[contentId]
            banner.withLogoImageHash(currentAsset?.logoImageHash)
            banner.withTitle(currentAsset?.title)
            banner.withTitleExtension(currentAsset?.titleExtension)
            banner.withBody(currentAsset?.body)
            banner.withHref(currentAsset?.bannerHref)


            currentAsset?.button?.let {
                banner.withButtonAction(ButtonAction.valueOf(it.action.name.uppercase()))
                banner.withButtonCaption(it.customText)
                banner.withButtonHref(it.href)
            }

            banner.withPixels(currentAsset?.pixels)
            banner.withMeasurers(currentAsset?.measurers?.map {
                BannerMeasurer()
                    .withBannerMeasurerSystem(BannerMeasurerSystem.valueOf(it.measurerType.name))
                    .withParams(it.params)
            })
        }
        return banner
    }

    fun cpmAdGroup(
        createDataContainer: UacModifyCampaignDataContainer,
        mediaType: MediaType
    ): AdGroup {
        return when (mediaType) {
            MediaType.VIDEO -> cpmVideoAdGroup(createDataContainer)
            MediaType.HTML5 -> cpmBannerAdGroup()
            else -> throw IllegalStateException("Illegal media (creative) type $mediaType")
        }
    }

    fun cpmVideoAdGroup(createDataContainer: UacModifyCampaignDataContainer): CpmVideoAdGroup {
        return CpmVideoAdGroup()
            .withType(AdGroupType.CPM_VIDEO)
            .withCriterionType(CriterionType.USER_PROFILE)
            .withMinusKeywords(emptyList())
            .withTags(emptyList())
            .withIsNonSkippable(false)
            .withProjectParamConditions(emptyList())
            .withPageGroupTags(emptyList())
            .withIsNonSkippable(createDataContainer.videosAreNonSkippable)
            .withTargetTags(emptyList())
    }

    fun cpmBannerAdGroup(): CpmBannerAdGroup {
        return CpmBannerAdGroup()
            .withType(AdGroupType.CPM_BANNER)
            .withCriterionType(CriterionType.USER_PROFILE)
            .withMinusKeywords(emptyList())
            .withTags(emptyList())
            .withProjectParamConditions(emptyList())
            .withPageGroupTags(emptyList())
            .withTargetTags(emptyList())
            .withForInBanners(false)
    }
}
