<template>
	<a
		v-if="campaign"
		:href="campaign.url"
		target="_blank"
		class="campaign"
	>
		<img
			v-if="campaign.banner.entity.type === 'network'"
			:src="`/img/banners/${campaign.banner.entity.slug}/${campaign.banner.id}.jpeg`"
			class="campaign-banner"
		>

		<img
			v-if="campaign.banner.entity.type === 'channel' && campaign.banner.entity.parent?.type === 'network'"
			:src="`/img/banners/${campaign.banner.entity.parent.slug}/${campaign.banner.entity.slug}/${campaign.banner.id}.jpeg`"
			class="campaign-banner"
		>
	</a>
</template>

<script>
function entityCampaign() {
	const bannerCampaigns = this.entity.campaigns
		.concat(this.entity.children?.flatMap(child => child.campaigns))
		.concat(this.entity.parent?.campaigns)
		.filter(campaignX => campaignX.banner?.ratio > 3);

	if (bannerCampaigns.length > 0) {
		return bannerCampaigns[Math.floor(Math.random() * bannerCampaigns.length)];
	}

	return null;
}

function tagCampaign() {
	const campaignBanners = this.tag.banners.filter(banner => banner.campaigns.length > 0 && banner.ratio > 3);
	const banner = campaignBanners[Math.floor(Math.random() * campaignBanners.length)];

	if (banner?.campaigns.length > 0) {
		return {
			...banner.campaigns[Math.floor(Math.random() * banner.campaigns.length)],
			banner,
		};
	}

	return null;
}

function campaign() {
	if (this.entity) {
		return this.entityCampaign();
	}

	if (this.tag) {
		return this.tagCampaign();
	}

	return null;
}

export default {
	props: {
		entity: {
			type: Object,
			default: null,
		},
		tag: {
			type: Object,
			default: null,
		},
	},
	computed: {
		campaign,
	},
	methods: {
		entityCampaign,
		tagCampaign,
	},
};
</script>

<style lang="scss" scoped>
.campaign {
	height: 100%;
	display: inline-flex;
	flex-grow: 1;
	align-items: center;
	justify-content: center;
}

.campaign-banner {
	max-height: 100%;
	max-width: 100%;
}
</style>
