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

<script>
import { FontAwesomeIcon as Icon } from '@fortawesome/vue-fontawesome'
export default {
	name: 'CustomCheckbox',
	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
			}
			if (Array.isArray(this.modelValue)) {
				return this.modelValue.includes(this.value)
			}
			return !!this.modelValue
		},
		iconToShow() {
			return this.state ? ['fas', 'check-square'] : ['far', 'square']
		}
	},
	methods: {
		onChange() {
			this.toggle()
		},
		toggle() {
			let value
			if (Array.isArray(this.modelValue)) {
				value = this.modelValue.slice(0)
				if (this.state) {
					value.splice(value.indexOf(this.value), 1)
				} else {
					value.push(this.value)
				}
			} else {
				value = !this.state
			}
			this.$emit('input', value)
		}
	},
	mounted() {
		if (this.checked && !this.state) {
			this.toggle()
		}
	},
	watch: {
		checked(n, o) {
			if (n != this.state) {
				this.toggle()
			}
		}
	}
}
</script>
