<script lang="ts">
	let tag = "";

	export let tags: any[] = [];
	export let addKeys: number[] = [13, 32];
	export let maxTags: number = Infinity;
	export let onlyUnique: boolean = false;
	export let removeKeys: number[] = [8];
	export let placeholder: string = "";
	export let allowPaste: boolean = true;
	export let allowDrop: boolean = false;
	export let splitWith: string = ",";
	export let name: string = "";
	export let disable: boolean = false;
	export let minlength: number = 0;
	export let maxlength: number = Infinity;
	export let readonly: boolean = false;
	export let onTagClick: Function = ()=>{};
	export let onFocusIn: () => any = () => {};
	export let onFocusOut: () => any = () => {};
	export let className: string = "";

	function addTag(tag: string) {
		if ((onlyUnique && tags.indexOf(tag) > -1) || maxTags == tags.length) {
			tag = "";
			return;
		}

		if (minlength > tag.toString().length || tag.toString().length > maxlength) {
			return;
		}

		tags = [...tags, tag].sort((a,b) => a-b);
	}

	function removeTag(i: number) {
		tags = tags.filter((_, index) => index !== i);
	}

	function onKeydown(e: KeyboardEvent) {
		if (addKeys.indexOf(e.keyCode) > -1) {
			e.preventDefault();
			addTag(tag);
			tag = "";
		} else if (removeKeys.indexOf(e.keyCode) > -1 && tag.length == 0) {
			e.preventDefault();
			removeTag(tags.length - 1);
			tag = ""
		}
	}
</script>

<div
	class="flex flex-row h-10 p-0"
>
	{#if tags.length > 0}
		{#each tags as tag, i}
			<button class="bg-white px-1.5 border border-gray-300 flex flex-row items-center justify-between gap-2" type="button" on:click={onTagClick(tag)}>
				{tag}
				{#if !disable && !readonly}
					<span
						on:pointerdown={() => removeTag(i)}
					>
						&#215;</span
					>
				{/if}
			</button>
		{/each}
	{/if}
	<input
		type="number"
		{name}
		bind:value={tag}
		on:keydown={onKeydown}
		on:focusin={onFocusIn}
		on:focusout={onFocusOut}
		on:blur={() => {
			if (tag.toString().length >= minlength && tag.toString().length <= maxlength) {
				addTag(tag)
				tag = ""
			}
		}}
		class="input input-bordered h-10 px-2 py-1.5 {className}"
		{minlength}
		{maxlength}
		disabled={disable}
		readonly={readonly}
		autocomplete="off"
		{...$$restProps}
	/>
</div>
