<template>
	<Tooltip class="filter-container">
		<div class="filter">
			<Icon icon="users" />

			<div
				v-if="selectedActors.length > 0"
				class="filter-applied"
			>{{ selectedActors.length }} {{ selectedActors.length > 1 ? 'actors' : 'actor' }}</div>

			<div
				v-else
				class="filter-applied empty"
			>Actors</div>
		</div>

		<template v-slot:tooltip>
			<div @click.stop>
				<router-link
					class="filter-clear"
					:to="{ query: { ...$route.query, actors: undefined } }"
					:class="{ active: selectedActors.length > 0 }"
				>clear all<Icon icon="cross2" /></router-link>

				<ul class="filter-items nolist">
					<li
						v-for="actor in availableActors"
						:key="actor.id"
						class="filter-item"
						:class="{ selected: selectedActors.includes(actor.slug) }"
					>
						<router-link
							:to="{ query: {
								...$route.query,
								actors: actor.slug,
							}, params: { pageNumber: 1 } }"
							class="filter-name"
						>{{ actor.name }}</router-link>

						<router-link
							:to="{ query: { ...$route.query, ...getNewRange(actor) }, params: { pageNumber: 1 } }"
							class="filter-include"
						>
							<Icon
								icon="checkmark"
								class="filter-add"
							/>

							<Icon
								icon="cross2"
								class="filter-remove"
							/>
						</router-link>
					</li>
				</ul>
			</div>
		</template>
	</Tooltip>
</template>

<script>
function getNewRange(actor) {
	if (this.selectedActors.includes(actor.slug)) {
		return { actors: this.selectedActors.filter(selectedActor => selectedActor !== actor.slug).join(',') || undefined };
	}

	return { actors: this.selectedActors.concat(actor.slug).join(',') };
}

function selectedActors() {
	return this.$route.query.actors ? this.$route.query.actors.split(',') : [];
}

export default {
	props: {
		availableActors: {
			type: Array,
			default: () => [],
		},
	},
	computed: {
		selectedActors,
	},
	methods: {
		getNewRange,
	},
};
</script>
