<template>
    <div>
		<NcSettingsSection
			name="Groupfolder Filesystem Snapshots"
			:limit-width="false">
			<div v-if="!loading">
				<Field :is="getAppSettingComponent(setting)"
					v-for="setting in app_settings"
					v-bind="getAppSettingProps(setting)"
					:key="setting.id"
					class="settings_field"
					:value="settings?.[setting.id]"
					@update:modelValue="(newValue) => updateSetting(setting.id, newValue)"
					@update:value="(newValue) => updateSetting(setting.id, newValue)" />
			</div>
		</NcSettingsSection>
	</div>
</template>
<script setup>
import { ref } from "vue";
import debounceFunction from 'debounce-fn';
import { NcSettingsSection, NcTextField, NcPasswordField, NcSelect } from "@nextcloud/vue"

import { adminSettingsApi } from "./adminSettingsApi.js";

let loading = ref(true);
let settings = ref({});

const app_settings = [
	{id: "filesystem_mountpoint_path", name: "Filesystem Mountpoint Path", type: "text" },
	{id: "filesystem_snapshots_path", name: "Filesystem Snapshots Path", type: "text"},
	{
		id: "snapshot_naming_scheme",
		name: "Snapshot Naming Scheme",
		type: "select",
		options: [
			{
				id: '',
				label: 'None',
			},
			{
				id: 'zfs-auto-snapshot',
				label: 'zfs-auto-snapshot',
			},
		]
	},
];

const getAppSettingComponent = function(appSetting) {
	if(appSetting.type === "select") {
		return NcSelect;
	} else {
		if(appSetting?.sensitive) {
			return NcPasswordField;
		} else {
			return NcTextField;
		}
	}
}

const getAppSettingProps = function(appSetting) {
	if(appSetting.type === "select") {
		return {
			options: appSetting.options,
			label: "label",
			inputLabel: appSetting.name,
			reduce: (option) => ( option.id )
		};
	} else {
		return {
			label: appSetting.name,
			clearable: false,
		};
	}
}

adminSettingsApi.getAllSettings().then((result) => {
	settings.value = result;
	loading.value = false;
});

const updateSetting = debounceFunction((key, value) => {
	console.log("updateSetting", key, value);
	settings.value[key] = value;
	adminSettingsApi.setSetting(key, value).then(() => {
	});
})

</script>
<style scoped>
.settings_field {
	margin-bottom: 20px;
}
</style>