<template>
	<div
		v-if="user"
		class="bookmarks"
	>
		<div
			v-if="showSecondary && !!itemAlerts"
			class="alert-trigger"
		>
			<Icon
				v-if="itemAlerted"
				icon="bell2"
				:title="`Remove ${itemAlerts.only.length} uncombined alert${itemAlerts.only.length > 1 ? 's' : ''} for '${item.title || item.name}'`"
				class="alert active noselect"
				@click="removeAlert"
				@contextmenu.prevent="showAlertDialog = true"
			/>

			<Icon
				v-else-if="itemAlerts.multi.length > 0"
				icon="bell-plus"
				:title="`Set alert for '${item.title || item.name}', ${itemAlerts.multi.length} combined alert${itemAlerts.multi.length > 1 ? 's' : ''} active`"
				class="alert partial noselect"
				@click="alertItem"
				@contextmenu.prevent="showAlertDialog = true"
			/>

			<Icon
				v-else
				icon="bell-plus"
				:title="`Set alert for '${item.title || item.name}' releases`"
				class="alert noselect"
				@click="alertItem"
				@contextmenu.prevent="showAlertDialog = true"
			/>
		</div>

		<VDropdown
			v-if="itemStashes && (showSecondary || (hasSecondaryStash && pageStash?.user.id !== user.id))"
			:shown="showStashes"
			@hide="showStashes = false"
		>
			<Icon
				icon="folder-heart"
				class="heart noselect"
				:class="{ favorited: itemStashes.some((itemStash) => !itemStash.isPrimary) }"
				@contextmenu.prevent="showStashes = true"
			/>

			<template #popper>
				<StashMenu
					:stashes="stashes"
					:item-stashes="itemStashes"
					@stash="(stash) => stashItem(stash)"
					@unstash="(stash) => unstashItem(stash)"
					@create="showStashDialog = true"
				/>
			</template>
		</VDropdown>

		<VDropdown
			v-if="itemStashes && (showSecondary || !hasSecondaryStash || pageStash?.user.id === user.id)"
			:triggers="[]"
			:shown="showStashes"
			:disabled="showSecondary"
			@hide="showStashes = false"
		>
			<template v-if="pageStash?.user.id === user.id">
				<Icon
					v-if="itemStashes.some((itemStash) => itemStash.id === pageStash.id)"
					:icon="pageStash.isPrimary ? 'heart7' : 'folder-heart'"
					class="heart favorited noselect"
					@click.native.stop="unstashItem(pageStash)"
					@contextmenu.prevent="toggleShowStashes(true)"
				/>

				<Icon
					v-else
					:icon="pageStash.isPrimary ? 'heart8' : 'folder-heart'"
					class="heart noselect"
					@click.native.stop="stashItem(pageStash)"
					@contextmenu.prevent="toggleShowStashes(true)"
				/>
			</template>

			<template v-else>
				<Icon
					v-if="itemStashes.some((itemStash) => itemStash.id === primaryStash.id)"
					icon="heart7"
					class="heart favorited noselect"
					@click.native.stop="unstashItem(primaryStash)"
					@contextmenu.prevent="toggleShowStashes(true)"
				/>

				<Icon
					v-else
					icon="heart8"
					class="heart noselect"
					@click.native.stop="stashItem(primaryStash)"
					@contextmenu.prevent="toggleShowStashes(true)"
				/>
			</template>

			<template #popper>
				<StashMenu
					:stashes="stashes"
					:item-stashes="itemStashes"
					@stash="(stash) => stashItem(stash)"
					@unstash="(stash) => unstashItem(stash)"
					@create="showStashDialog = true"
				/>
			</template>
		</VDropdown>

		<StashDialog
			v-if="showStashDialog"
			@created="(newStash) => { showStashDialog = false; reloadStashes(newStash); }"
			@close="showStashDialog = false;"
		/>

		<AlertDialog
			v-if="showAlertDialog"
			v-bind="{ [`preset-${domain}`]: [item] }"
			@close="showAlertDialog = false;"
			@alert="(alert) => setAlerted(alert)"
		/>
	</div>
</template>

<script setup>
import { ref, computed, inject } from 'vue';

import { get, post, del } from '#/src/api.js';
import ellipsis from '#/utils/ellipsis.js';

import Icon from '#/components/icon/icon.vue';
import StashMenu from '#/components/stashes/menu.vue';
import StashDialog from '#/components/stashes/create.vue';
import AlertDialog from '#/components/alerts/create.vue';

const props = defineProps({
	domain: {
		type: String,
		default: 'scenes',
	},
	item: {
		type: Object,
		default: null,
	},
	showSecondary: {
		type: Boolean,
		default: true,
	},
});

const emit = defineEmits(['stashed', 'unstashed']);

const pageContext = inject('pageContext');
const pageStash = pageContext.pageProps.stash;
const user = pageContext.user;

const stashes = ref(pageContext.assets?.stashes);
const primaryStash = pageContext.assets?.primaryStash;
const itemStashes = ref(props.item.stashes);
const itemAlerts = ref(props.item.alerts);
const itemAlerted = ref(props.item.alerts?.only.length > 0);
const hasSecondaryStash = computed(() => itemStashes.value.some((itemStash) => !itemStash.isPrimary));

const done = ref(true);
const showStashes = ref(false);
const showStashDialog = ref(false);
const showAlertDialog = ref(false);
const feedbackCutoff = 20;

const itemKeys = {
	scenes: 'sceneId',
	actors: 'actorId',
	movies: 'movieId',
};

async function stashItem(stash) {
	if (!done.value) {
		return;
	}

	const stashState = itemStashes.value;

	done.value = false;
	itemStashes.value = itemStashes.value.concat(stash);

	try {
		await post(`/stashes/${stash.id}/${props.domain}`, { [itemKeys[props.domain]]: props.item.id }, {
			successFeedback: `"${ellipsis(props.item.title || props.item.name, feedbackCutoff)}" stashed to ${stash.name}`,
			errorFeedback: `Failed to stash "${ellipsis(props.item.title || props.item.name, feedbackCutoff)}" to ${stash.name}`,
		});

		emit('stashed', stash);
	} catch (error) {
		itemStashes.value = stashState;
	} finally {
		done.value = true;
	}
}

async function unstashItem(stash) {
	if (!done.value) {
		return;
	}

	const stashState = itemStashes.value;

	done.value = false;
	itemStashes.value = itemStashes.value.filter((itemStash) => itemStash.id !== stash.id);

	try {
		await del(`/stashes/${stash.id}/${props.domain}/${props.item.id}`, {
			undoFeedback: `"${ellipsis(props.item.title || props.item.name, feedbackCutoff)}" unstashed from ${stash.name}`,
			errorFeedback: `Failed to unstash "${ellipsis(props.item.title || props.item.name, feedbackCutoff)}" from ${stash.name}`,
		});

		emit('unstashed', stash);
	} catch (error) {
		itemStashes.value = stashState;
	} finally {
		done.value = true;
	}
}

async function alertItem() {
	if (!done.value) {
		return;
	}

	const alertLabel = props.item.title || props.item.name;

	done.value = false;
	itemAlerted.value = true;

	try {
		const newAlert = await post('/alerts', {
			...(props.domain === 'actors' && { actors: [props.item.id] }),
			...(props.domain === 'tags' && { tags: [props.item.id] }),
			...(props.domain === 'entities' && { entities: [props.item.id] }),
			notify: true,
			email: false,
			preset: true,
		}, {
			successFeedback: `Alert set for '${alertLabel}'`,
			errorFeedback: `Failed to set alert for '${alertLabel}'`,
			appendErrorMessage: true,
		});

		itemAlerts.value.only = itemAlerts.value.only.concat(newAlert.id);
	} catch (error) {
		itemAlerted.value = false;
	} finally {
		done.value = true;
	}
}

async function removeAlert() {
	if (done.value === false) {
		return;
	}

	const alertLabel = props.item.title || props.item.name;
	const alertIds = itemAlerts.value.only;

	done.value = false;

	itemAlerted.value = false;
	itemAlerts.value.only = itemAlerts.value.only.filter((alertId) => !alertIds.includes(alertId));

	try {
		await del(`/alerts/${alertIds.join(',')}`, {
			undoFeedback: `Removed alert for '${alertLabel}'`,
			errorFeedback: `Failed to remove alert for '${alertLabel}'`,
			appendErrorMessage: true,
		});
	} catch (error) {
		itemAlerted.value = true;
		itemAlerts.value.only = itemAlerts.value.only.concat(alertIds);
	} finally {
		done.value = true;
	}
}

function setAlerted(alert) {
	// only set alerted status if the current item is the only one in the new stash
	const items = [...alert.actors, ...alert.tags, ...alert.entities, ...alert.matches];

	if (items.length === 1 && alert[props.domain][0]?.id === props.item.id) {
		itemAlerted.value = true;
		itemAlerts.value.only = itemAlerts.value.only.concat(alert.id);
	} else {
		itemAlerts.value.multi = itemAlerts.value.multi.concat(alert.id);
	}
}

function toggleShowStashes(state) {
	if (props.showSecondary) {
		return;
	}

	if (state) {
		showStashes.value = state;
		return;
	}

	showStashes.value = !showStashes.value;
}

async function reloadStashes(newStash) {
	stashes.value = await get(`/users/${user.id}/stashes`);

	await stashItem(newStash);
}
</script>

<style scoped>
.bookmarks {
	display: flex;

	.icon {
		width: 1.5rem;
		height: auto; /* prevents jumping */
		padding: .5rem .5rem;
		fill: var(--glass);
	}

	&.light .icon {
		fill: var(--highlight);
	}

	&.tiled {
		position: absolute;
		top: 0;
		right: 0;

		.icon {
			fill: var(--highlight-strong-20);
			filter: drop-shadow(0 0 3px var(--shadow-strong-10));
		}
	}

	.icon.alert {
		width: 1.3rem;
		padding: .7rem .5rem;
	}

	.icon.heart:hover,
	.icon.alert:hover,
	.icon.heart.favorited,
	.icon.alert.active {
		cursor: pointer;
		fill: var(--primary);
	}

	.icon.alert.partial {
		cursor: pointer;
		fill: var(--text-light);
	}
}

.alert-trigger:not(:last-child) {
	padding-right: .25rem;
	border-right: solid 1px var(--highlight-weak-30);
	margin-right: .25rem;
}
</style>