
<template>
	<div v-if="display"
		class="property-select"
		:class="{ 'property-select--readonly': isReadOnly }">
		<component :is="icon"
			:size="20"
			:name="readableName"
			class="property-select__icon"
			:class="{ 'property-select__icon--hidden': !showIcon }" />

		<div class="property-select__input"
			:class="{ 'property-select__input--readonly': isReadOnly }">
			<NcSelect v-if="!isReadOnly"
				:options="options"
				:searchable="true"
				:multiple="false"
				:taggable="false"
				:name="readableName"
				:value="selectedValue"
				:placeholder="placeholder"
				:clearable="true"
				:labelOutside="true"
				input-id="value"
				label="label"
				@input="changeValue" />
			<!-- eslint-disable-next-line vue/singleline-html-element-content-newline -->
			<div v-else>{{ selectedValue.label }}</div>
		</div>

		<div v-if="hasInfo"
			v-tooltip="info"
			class="property-select__info">
			<InformationVariant :size="20"
				decorative />
		</div>
	</div>
</template>

<script>
import PropertyMixin from '../../../mixins/PropertyMixin.js'
import { NcSelect } from '@nextcloud/vue'

import InformationVariant from 'vue-material-design-icons/InformationVariant.vue'
import {generateUrl} from "@nextcloud/router";
import axios from "@nextcloud/axios";
import {decode} from 'html-entities';

export default {
	name: 'PropertySelectLieu',
	components: {
		NcSelect,
		InformationVariant,
	},
	props: {
		url: {
			type: String,
			required: false,
		},
	},
	data() {
		return {
			properties: [], // Data to populate the dropdown
			selectedProperty: null, // Currently selected property
		};
	},
	mixins: [
		PropertyMixin,
	],
	computed: {
		display() {
			return true
		},
		options() {
			return this.properties
		},
		selectedValue() {
			const value = this.value || this.propModel.defaultValue
			return this.properties.find((option) => option.value.toString() === value)
		},
	},
	mounted() {
		this.fetchProperties(); // Fetch data when the component is mounted
	},
	methods: {
		fetchProperties() {
			const ajaxUrl = generateUrl(this.url)
			axios.get(ajaxUrl)
				.then((response) => {
					let results = JSON.parse(response.data)
					let values = []
					results.forEach(result => {
                        let inputValue = decode(result.id)
                        let inputLabel = decode(result.nom)
                        values.push({
                            value : inputValue.toString(),
                            label :inputLabel
                        })
					})
					this.properties = values
				})
				.catch(error => {
					console.error('Error fetching properties:', error);
				});
		},
		changeValue(selectedOption) {
			if (!selectedOption) {
				return
			}

			this.$emit('update:value', selectedOption.value)
		},
	},
}
</script>

<style lang="scss" scoped>

.property-select {
	&__input {
		// 34px left and right need to be subtracted. See https://github.com/nextcloud/calendar/pull/3361
		width: calc(100% - 34px - 34px);
	}
}

</style>
