<template>
<label :for="id" @click.stop="$emit('click')" @dblclick.stop="$emit('dblclick')" :class="{ 'radiocheckbox2': true, 'state-disabled': disabled || !editable }">
    <input type="radio" :id="id" :ref="id" :name="name" :value="value" @change="onChange" :checked="state" :disabled="disabled || !editable"/>
    <span class="radio"><Icon :icon="iconToShow" class="icon"/></span>
    <slot></slot>
</label>
</template>

<script>
import { FontAwesomeIcon as Icon } from '@fortawesome/vue-fontawesome'
export default {
	name: 'CustomRadio',
	components: {
		Icon
	},
	props: {
		// Unique identifier
		id: {
			type: String,
			required: true
		},
		// Value binding for the component
		value: {
			default: null
		},
		// Useful for radio groups
		name: {
			type: String,
			required: true
		},
		disabled: {
			type: Boolean,
			default: false
		},
		checked: {
			type: Boolean,
			default: false
		},
		modelValue: {
			default: undefined
		},
		editable: {
			type: Boolean,
			default: true
		}
	},
	model: {
		prop: 'modelValue',
		event: 'input'
	},
	computed: {
		state() {
			if (this.modelValue === undefined) {
				return this.checked
			}
			return this.modelValue == this.value
		},
		iconToShow() {
			return this.state ? ['fabt', 'circle-radio'] : ['fabt', 'circle-empty']
		}
	},
	methods: {
		onChange() {
			this.toggle()
		},
		toggle() {
			this.$emit('input', this.state ? '' : this.value)
		}
	},
	mounted() {
		if (this.checked && !this.state) {
			this.toggle()
		}
	},
	watch: {
		checked(n, o) {
			if (n != this.state) {
				this.toggle()
			}
		}
	}
}
</script>
