<script>
	import {generate_random_hex_color} from "$shared/lib/colors";
	import labels, {reload_labels, create_label_async} from "$app/lib/stores/labels";
	import Dropdown from "$shared/components/dropdown.svelte";

	let labelsError = "";
	let loading = false;
	let DropdownExports;

	function reset() {
		DropdownExports.reset();
		console.log("Reset labels-part");
	}

	function get_selected() {
		return $labels.filter((c) => Object.hasOwn(c, "selected") && c.selected === true);
	}

	function select_label(id) {
		DropdownExports.select(id);
	}

	function select_labels(ids) {
		for (const id of ids) {
			DropdownExports.select(id);
		}
	}

	async function on_create({name}) {
		loading = true;
		const response = await create_label_async({
			name: name,
			color: generate_random_hex_color(),
		});
		loading = false;
		if (response.ok) {
			// Small pause to allow loading state to update everywhere.
			setTimeout(() => select_label(response.data.id), 50);
		}
	}

	export const functions = {
		get_selected,
		reset,
		load_labels: reload_labels,
		select_labels,
		select_label,
	};
</script>

<Dropdown
        entries={$labels}
        label="Labels"
        maxlength="50"
        createable={true}
        placeholder="Search or create"
        multiple="{true}"
        id="labels-search"
        name="labels-search"
        on_create_async={on_create}
        noResultsText="No labels available (Create a new one by searching for it and pressing enter)"
        errorText="{labelsError}"
        bind:this={DropdownExports}
        {loading}
/>
