<!-- Used as Fetch From Control -->
<script setup>
import { useStore } from "../../store";
import { load_pagetype_model } from "../../utils";
import { ref, computed, watch } from "vue";
import { computedAsync } from "@vueuse/core";

let store = useStore();
const props = defineProps(["df", "value", "read_only", "modelValue"]);
let emit = defineEmits(["update:modelValue"]);

let pagetype = ref("");
let fieldname = ref("");
let pagetypes = ref("");

let pagetype_df = computed(() => {
	pagetypes.value = store
		.get_updated_fields()
		.filter((df) => df.fieldtype == "Link")
		.filter((df) => df.options && df.fieldname != store.form.selected_field.fieldname)
		.sort((a, b) => a.options.localeCompare(b.options))
		.map((df) => ({
			label: `${df.options} (${df.fieldname})`,
			value: df.fieldname,
			pagetype_name: df.options,
		}));

	let options = [{ label: __("Select PageType"), value: "" }, ...pagetypes.value];
	return { fieldtype: "Select", label: __("Fetch From"), options };
});

let field_df = computedAsync(async () => {
	let options = [{ label: __("Select Field"), value: "" }];
	let df = { fieldtype: "Select", label: __("Fetch From"), options };
	if (!pagetype.value) return df;
	let pagetype_name = pagetypes.value?.find((df) => df.value == pagetype.value).pagetype_name;
	if (!pagetype_name) return df;

	if (props.value.split(".")[0] != pagetype.value) {
		fieldname.value = "";
	}

	await load_pagetype_model(pagetype_name);

	let fields = jingrow.meta
		.get_pagefields(pagetype_name, null, {
			fieldtype: ["not in", jingrow.model.no_value_type],
		})
		.sort((a, b) => {
			if (a.label && b.label) {
				return a.label.localeCompare(b.label);
			}
		})
		.map((df) => ({
			label: `${df.label || __("No Label")} (${df.fieldtype})`,
			value: df.fieldname,
		}));

	df.options = df.options.concat(fields);
	return df;
}, {});

watch(
	() => props.value,
	(value) => {
		if (value) [pagetype.value, fieldname.value] = value.split(".") || ["", ""];
	},
	{ immediate: true }
);

watch([() => pagetype.value, () => fieldname.value], ([pagetype_value, fieldname_value]) => {
	let [pagetype_name, field_name] = props.value?.split(".") || ["", ""];
	if (pagetype_value != pagetype_name || fieldname_value != field_name) {
		let fetch_expression = "";
		if (pagetype_value && fieldname_value) {
			fetch_expression = `${pagetype_value}.${fieldname_value}`;
		}
		emit("update:modelValue", fetch_expression);
	}
});
</script>

<template>
	<div>
		<SelectControl
			:df="pagetype_df"
			:value="pagetype"
			:read_only="read_only"
			v-model="pagetype"
		/>
		<SelectControl
			v-if="pagetype"
			:df="field_df"
			:read_only="read_only"
			:value="fieldname"
			v-model="fieldname"
			:no_label="true"
		/>
	</div>
</template>
