import { useWorkspace } from "../../../store/store.js";
import ViewLayoutCollapse_default from "../../../components/ViewLayout/ViewLayoutCollapse.vue.js";
import RequestTable_default from "./RequestTable.vue.js";
import { computed, createBlock, createCommentVNode, createElementVNode, createTextVNode, createVNode, defineComponent, nextTick, normalizeClass, onMounted, openBlock, ref, toDisplayString, unref, watch, withCtx, withModifiers } from "vue";
import { ScalarButton, ScalarTooltip } from "@scalar/components";
import { requestExampleParametersSchema } from "@scalar/oas-utils/entities/spec";
//#region src/views/Request/RequestSection/RequestParams.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "text-c-2 request-meta-buttons flex whitespace-nowrap opacity-0 group-hover/params:opacity-100 has-[:focus-visible]:opacity-100" };
var _hoisted_2 = { class: "sr-only" };
var RequestParams_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "RequestParams",
	props: {
		example: {},
		environment: {},
		envVariables: {},
		workspace: {},
		title: {},
		label: {},
		paramKey: {},
		readOnlyEntries: { default: () => [] },
		invalidParams: {}
	},
	setup(__props) {
		const { requestExampleMutators } = useWorkspace();
		const params = computed(() => __props.example.parameters[__props.paramKey] ?? []);
		onMounted(() => {
			nextTick(() => {
				defaultRow();
			});
		});
		/** Add a new row to a given parameter list */
		const addRow = () => {
			/** Create a new parameter instance with 'enabled' set to false */
			const newParam = requestExampleParametersSchema.parse({ enabled: false });
			const newParams = [...params.value, newParam];
			requestExampleMutators.edit(__props.example.uid, `parameters.${__props.paramKey}`, newParams);
		};
		const tableWrapperRef = ref(null);
		/** Update a field in a parameter row */
		const updateRow = (rowIdx, field, value) => {
			const currentParams = params.value;
			if (currentParams.length > rowIdx) {
				const updatedParams = [...currentParams];
				if (!updatedParams[rowIdx]) return;
				updatedParams[rowIdx] = {
					...updatedParams[rowIdx],
					[field]: value
				};
				/** enable row key or value is filled */
				if (updatedParams[rowIdx].key !== "" || updatedParams[rowIdx].value !== "") updatedParams[rowIdx].enabled = true;
				/** check key and value input state */
				if (updatedParams[rowIdx].key === "" && updatedParams[rowIdx].value === "")
 /** remove if empty */
				updatedParams.splice(rowIdx, 1);
				requestExampleMutators.edit(__props.example.uid, `parameters.${__props.paramKey}`, updatedParams);
			} else {
				/** if there is no row at the index, add a new one */
				const payload = [requestExampleParametersSchema.parse({ [field]: value })];
				requestExampleMutators.edit(__props.example.uid, `parameters.${__props.paramKey}`, payload);
				/** focus the new row */
				nextTick(() => {
					if (!tableWrapperRef.value) return;
					tableWrapperRef.value.querySelectorAll("input")[field === "key" ? 0 : 1]?.focus();
				});
			}
			if (rowIdx === currentParams.length - 1) addRow();
		};
		/** Toggle a parameter row on or off */
		const toggleRow = (rowIdx, enabled) => requestExampleMutators.edit(__props.example.uid, `parameters.${__props.paramKey}.${rowIdx}.enabled`, enabled);
		const deleteAllRows = () => {
			const exampleParams = params.value.filter((param) => param.required);
			requestExampleMutators.edit(__props.example.uid, `parameters.${__props.paramKey}`, exampleParams);
			/** ensure one empty row after deleting all rows */
			nextTick(() => addRow());
		};
		const deleteRow = (rowIdx) => {
			const currentParams = params.value;
			if (currentParams.length > rowIdx) {
				const updatedParams = [...currentParams];
				updatedParams.splice(rowIdx, 1);
				requestExampleMutators.edit(__props.example.uid, `parameters.${__props.paramKey}`, updatedParams);
			}
		};
		function defaultRow() {
			/** ensure one empty row by default */
			if (params.value.length === 0) addRow();
			else if (params.value.length >= 1) {
				/** ensure we always have a trailing empty row */
				const lastParam = params.value[params.value.length - 1];
				if (lastParam && lastParam.key !== "" && lastParam.value !== "") addRow();
			}
		}
		const itemCount = computed(() => params.value.filter((param) => param.key || param.value).length);
		const showTooltip = computed(() => params.value.length > 1);
		watch(() => __props.example, (newVal, oldVal) => {
			if (newVal !== oldVal) defaultRow();
		}, { immediate: true });
		const hasReadOnlyEntries = computed(() => (__props.readOnlyEntries ?? []).length > 0);
		return (_ctx, _cache) => {
			return openBlock(), createBlock(ViewLayoutCollapse_default, {
				class: "group/params",
				itemCount: itemCount.value
			}, {
				title: withCtx(() => [createTextVNode(toDisplayString(__props.title), 1)]),
				actions: withCtx(() => [createElementVNode("div", _hoisted_1, [showTooltip.value ? (openBlock(), createBlock(unref(ScalarTooltip), {
					key: 0,
					content: "Clear optional parameters",
					placement: "left"
				}, {
					default: withCtx(() => [createVNode(unref(ScalarButton), {
						class: "pr-0.75 pl-1 transition-none",
						size: "sm",
						variant: "ghost",
						onClick: withModifiers(deleteAllRows, ["stop"])
					}, {
						default: withCtx(() => [_cache[0] || (_cache[0] = createTextVNode(" Clear ", -1)), createElementVNode("span", _hoisted_2, "All " + toDisplayString(__props.title), 1)]),
						_: 1
					})]),
					_: 1
				})) : createCommentVNode("", true)])]),
				default: withCtx(() => [createElementVNode("div", {
					ref_key: "tableWrapperRef",
					ref: tableWrapperRef
				}, [hasReadOnlyEntries.value ? (openBlock(), createBlock(RequestTable_default, {
					key: 0,
					class: normalizeClass(["flex-1", { "bg-c-3/5": hasReadOnlyEntries.value }]),
					columns: [
						"32px",
						"",
						""
					],
					envVariables: __props.envVariables,
					environment: __props.environment,
					invalidParams: __props.invalidParams,
					isGlobal: "",
					isReadOnly: "",
					items: __props.readOnlyEntries,
					label: __props.label,
					workspace: __props.workspace
				}, null, 8, [
					"class",
					"envVariables",
					"environment",
					"invalidParams",
					"items",
					"label",
					"workspace"
				])) : createCommentVNode("", true), createVNode(RequestTable_default, {
					class: "flex-1",
					columns: [
						"32px",
						"",
						""
					],
					envVariables: __props.envVariables,
					environment: __props.environment,
					invalidParams: __props.invalidParams,
					items: params.value,
					label: __props.label,
					workspace: __props.workspace,
					onToggleRow: toggleRow,
					onUpdateRow: updateRow,
					onDeleteRow: deleteRow
				}, null, 8, [
					"envVariables",
					"environment",
					"invalidParams",
					"items",
					"label",
					"workspace"
				])], 512)]),
				_: 1
			}, 8, ["itemCount"]);
		};
	}
});
//#endregion
export { RequestParams_vue_vue_type_script_setup_true_lang_default as default };

//# sourceMappingURL=RequestParams.vue.script.js.map