<script setup>
import {ref, watch} from "vue";
import TSelect from "@/components/ui/TSelect.vue";
import TOption from "@/components/ui/TOption.vue";
import TInputText from "@/components/ui/TInputText.vue";

const props = defineProps(["v-name", "v-value", "v-count", "v-unit", "size", "maxlength", "v-supported-units"])
const emits = defineEmits(["change"])

const {capacity, countString, vSize, vMaxlength, supportedUnits} = (function () {
	let v = props.vValue
	if (v == null) {
		v = {
			count: props.vCount,
			unit: props.vUnit
		}
	}
	if (v.unit == null || v.unit.length == 0) {
		v.unit = "mb"
	}

	if (typeof (v["count"]) != "number") {
		v["count"] = -1
	}

	let vSize = props.size
	if (vSize == null) {
		vSize = 6
	}

	let vMaxlength = props.maxlength
	if (vMaxlength == null) {
		vMaxlength = 10
	}

	let supportedUnits = props.vSupportedUnits
	if (supportedUnits == null) {
		supportedUnits = []
	}

	return {
		capacity: ref(v),
		countString: ref((v.count >= 0) ? v.count.toString() : ""),
		vSize: ref(vSize),
		vMaxlength: ref(vMaxlength),
		supportedUnits: ref(supportedUnits)
	}
})()

const change = function () {
	emits("change", capacity.value)
}

watch(countString, function (newValue) {
	let value = newValue.trim()
	if (value.length == 0) {
		capacity.value.count = -1
		change()
		return
	}
	let count = parseInt(value)
	if (!isNaN(count)) {
		capacity.value.count = count
	}
	change()
})

</script>

<template>
	<div class="ui fields inline">
		<input type="hidden" :name="vName" :value="JSON.stringify(capacity)"/>
		<div class="ui field">
			<TInputText type="text" v-model="countString" :maxlength="vMaxlength" :size="vSize"/>
		</div>
		<div class="ui field">
			<TSelect v-model="capacity.unit" @change="change">
				<TOption value="b" v-if="supportedUnits.length == 0 || supportedUnits.$contains('b')">Bps</TOption>
				<TOption value="kb" v-if="supportedUnits.length == 0 || supportedUnits.$contains('kb')">Kbps</TOption>
				<TOption value="mb" v-if="supportedUnits.length == 0 || supportedUnits.$contains('mb')">Mbps</TOption>
				<TOption value="gb" v-if="supportedUnits.length == 0 || supportedUnits.$contains('gb')">Gbps</TOption>
				<TOption value="tb" v-if="supportedUnits.length == 0 || supportedUnits.$contains('tb')">Tbps</TOption>
				<TOption value="pb" v-if="supportedUnits.length == 0 || supportedUnits.$contains('pb')">Pbps</TOption>
				<TOption value="eb" v-if="supportedUnits.length == 0 || supportedUnits.$contains('eb')">Ebps</TOption>
			</TSelect>
		</div>
	</div>
</template>

<style scoped>

</style>