import { PathId } from "../../routes.js";
import { useActiveEntities } from "../../store/active-entities.js";
import { isUrl } from "../../libs/isUrl.js";
import { getOpenApiDocumentDetails } from "../../libs/getOpenApiDocumentDetails.js";
import { convertPostmanToOpenApi, getPostmanDocumentDetails, isPostmanCollection } from "../../libs/postman.js";
import { useWorkspace } from "../../store/store.js";
import { importCurlCommand } from "../../libs/importers/curl.js";
import CommandActionForm_default from "./CommandActionForm.vue.js";
import CommandActionInput_default from "./CommandActionInput.vue.js";
import { useFileDialog } from "../../hooks/useFileDialog.js";
import WatchModeToggle_default from "./WatchModeToggle.vue.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, openBlock, ref, toDisplayString, unref, watch, withCtx } from "vue";
import { ScalarButton, ScalarCodeBlock, ScalarIcon, ScalarTooltip, useLoadingState } from "@scalar/components";
import { useToasts } from "@scalar/use-toasts";
import { useRouter } from "vue-router";
//#region src/components/CommandPalette/CommandPaletteImport.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "flex justify-between" };
var _hoisted_2 = { class: "flex w-full flex-row items-center justify-between gap-3" };
var CommandPaletteImport_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "CommandPaletteImport",
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const emits = __emit;
		const router = useRouter();
		const { activeWorkspace, activeCollection } = useActiveEntities();
		const { importSpecFile, importSpecFromUrl, events } = useWorkspace();
		const { toast } = useToasts();
		const loader = useLoadingState();
		const inputContent = ref("");
		const watchMode = ref(true);
		const documentDetails = computed(() => {
			if (isPostmanCollection(inputContent.value)) return getPostmanDocumentDetails(inputContent.value);
			return getOpenApiDocumentDetails(inputContent.value);
		});
		const documentType = computed(() => documentDetails.value ? documentDetails.value.type : "json");
		function navigateToCollectionPage(collection) {
			if (!collection) return;
			router.push({
				name: "collection",
				params: {
					[PathId.Workspace]: activeWorkspace.value?.uid,
					[PathId.Collection]: collection.uid
				}
			});
		}
		const isInputUrl = computed(() => isUrl(inputContent.value));
		const isInputDocument = computed(() => !!documentDetails.value);
		const { open: openSpecFileDialog } = useFileDialog({
			onChange: (files) => {
				const file = files?.[0];
				if (file) {
					const reader = new FileReader();
					reader.onload = async (e) => {
						const text = e.target?.result;
						try {
							if (isPostmanCollection(text)) navigateToCollectionPage((await importSpecFile(convertPostmanToOpenApi(text), activeWorkspace.value?.uid ?? ""))?.collection);
							else navigateToCollectionPage((await importSpecFile(text, activeWorkspace.value?.uid ?? ""))?.collection);
							toast("Import successful", "info");
							emits("close");
						} catch (error) {
							console.error(error);
							toast(`Import failed: ${error?.message || "Unknown error"}`, "error");
						}
					};
					reader.readAsText(file);
				}
			},
			multiple: false,
			accept: ".json,.yaml,.yml"
		});
		watch(isInputUrl, (newVal) => {
			if (!newVal) watchMode.value = false;
		});
		watch(inputContent, (newVal) => {
			if (!isUrl(newVal)) watchMode.value = false;
		});
		async function importCollection() {
			if (!inputContent.value || loader.isLoading) return;
			loader.start();
			try {
				if (isInputUrl.value) {
					const [error, workspace] = await importSpecFromUrl(inputContent.value, activeWorkspace.value?.uid ?? "", {
						proxyUrl: activeWorkspace.value?.proxyUrl,
						watchMode: watchMode.value
					});
					navigateToCollectionPage(workspace?.collection);
					if (error) {
						toast("There was a possible CORS error while importing your spec, please make sure this server is allowed in the CORS policy of your OpenAPI document.", "error", { timeout: 5e3 });
						await loader.invalidate();
						return;
					}
				} else if (isInputDocument.value) if (isPostmanCollection(inputContent.value)) {
					navigateToCollectionPage((await importSpecFile(convertPostmanToOpenApi(inputContent.value), activeWorkspace.value?.uid ?? ""))?.collection);
					toast("Successfully converted Postman collection", "info");
				} else navigateToCollectionPage((await importSpecFile(inputContent.value, activeWorkspace.value?.uid ?? ""))?.collection);
				else {
					toast("Import failed: Invalid URL or OpenAPI document", "error");
					await loader.invalidate();
					return;
				}
				await loader.clear();
				emits("close");
				toast("Import successful", "info");
			} catch (error) {
				console.error("[importCollection]", error);
				const errorMessage = error?.message || "Unknown error";
				await loader.invalidate();
				toast(`Import failed: ${errorMessage}`, "error");
			}
		}
		const handleInput = (value) => {
			if (value.trim().toLowerCase().startsWith("curl")) {
				events.commandPalette.emit({
					commandName: "Import from cURL",
					metaData: {
						parsedCurl: importCurlCommand(value),
						collectionUid: activeCollection.value?.uid
					}
				});
				return;
			}
			inputContent.value = value;
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(CommandActionForm_default, {
				disabled: !inputContent.value.trim(),
				loader: unref(loader),
				onSubmit: importCollection
			}, {
				options: withCtx(() => [createElementVNode("div", _hoisted_2, [createVNode(unref(ScalarButton), {
					class: "hover:bg-b-2 relative max-h-8 gap-1.5 p-2 text-xs",
					variant: "outlined",
					onClick: unref(openSpecFileDialog)
				}, {
					default: withCtx(() => [_cache[5] || (_cache[5] = createTextVNode(" JSON, or YAML File ", -1)), createVNode(unref(ScalarIcon), {
						class: "text-c-3",
						icon: "Upload",
						size: "md"
					})]),
					_: 1
				}, 8, ["onClick"]), createVNode(unref(ScalarTooltip), {
					content: isInputUrl.value ? "Watch mode automatically updates the API client when the OpenAPI URL content changes, ensuring your client remains up-to-date." : "Watch mode is only available for URL imports. When enabled it automatically updates the API client when the OpenAPI URL content changes.",
					placement: "bottom"
				}, {
					default: withCtx(() => [createVNode(WatchModeToggle_default, {
						modelValue: watchMode.value,
						"onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => watchMode.value = $event),
						disabled: !isInputUrl.value
					}, null, 8, ["modelValue", "disabled"])]),
					_: 1
				}, 8, ["content"])])]),
				submit: withCtx(() => [_cache[6] || (_cache[6] = createTextVNode(" Import ", -1)), isInputUrl.value ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(" from URL ")], 64)) : documentDetails.value && documentType.value ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [documentDetails.value.title ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(" \"" + toDisplayString(documentDetails.value.title) + "\" ", 1)], 64)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode(toDisplayString(documentDetails.value.version), 1)], 64))], 64)) : (openBlock(), createElementBlock(Fragment, { key: 2 }, [createTextVNode(" Collection ")], 64))]),
				default: withCtx(() => [!documentDetails.value || unref(isUrl)(inputContent.value) ? (openBlock(), createBlock(CommandActionInput_default, {
					key: 0,
					modelValue: inputContent.value,
					placeholder: "OpenAPI/Swagger/Postman URL or cURL",
					onOnDelete: _cache[0] || (_cache[0] = ($event) => emits("back", $event)),
					"onUpdate:modelValue": handleInput
				}, null, 8, ["modelValue"])) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createElementVNode("div", _hoisted_1, [_cache[4] || (_cache[4] = createElementVNode("div", { class: "text-c-2 min-h-8 w-full py-2 pl-12 text-center text-xs" }, " Preview ", -1)), createVNode(unref(ScalarButton), {
					class: "hover:bg-b-2 relative ml-auto max-h-8 gap-1.5 p-2 text-xs",
					variant: "ghost",
					onClick: _cache[1] || (_cache[1] = ($event) => inputContent.value = "")
				}, {
					default: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Clear ", -1)])]),
					_: 1
				})]), documentDetails.value && !unref(isUrl)(inputContent.value) ? (openBlock(), createBlock(unref(ScalarCodeBlock), {
					key: 0,
					class: "bg-b-2 mt-1 max-h-[40dvh] rounded border px-2 py-1 text-sm",
					content: inputContent.value,
					copy: false,
					lang: documentType.value
				}, null, 8, ["content", "lang"])) : createCommentVNode("", true)], 64))]),
				_: 1
			}, 8, ["disabled", "loader"]);
		};
	}
});
//#endregion
export { CommandPaletteImport_vue_vue_type_script_setup_true_lang_default as default };

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