<script setup>

import useUtils from "@/utils/utils.js"
import {inject, onMounted, ref, watch} from "vue"
import TTag from "@/components/ui/TTag.vue";

const utils = useUtils()

const Tea = inject("$Tea")

const props = defineProps(["v-type", "v-value"])

const emits = defineEmits(["select"])

const {allHeaders, matchedHeaders, selectedHeaderName} = (function () {
	return {
		allHeaders: ref([]),
		matchedHeaders: ref([]),

		selectedHeaderName: ref("")
	}
})()

const select = function (header) {
	emits("select", header)
	selectedHeaderName.value = header
}

watch(() => props.vValue, function (v) {
	if (v != selectedHeaderName.value) {
		selectedHeaderName.value = ""
	}

	if (v.length == 0) {
		matchedHeaders.value = []
		return
	}
	matchedHeaders.value = allHeaders.value.filter(function (header) {
		return utils.match(header, v)
	}).slice(0, 10)
})

onMounted(() => {
	Tea.action("/servers/headers/options?type=" + props.vType)
		.post()
		.success(function (resp) {
			allHeaders.value = resp.data.headers
		})
})
</script>

<template>
<span v-if="selectedHeaderName.length == 0" class="inline-block label-group">
	<a href="" v-for="header in matchedHeaders" @click.prevent="select(header)"><TTag>{{ header }}</TTag></a>
	<span v-if="matchedHeaders.length > 0">&nbsp; &nbsp;</span>
</span>
</template>

<style scoped>
</style>
