<template>
	<div class="WM-Checkbox c-toggle-hide RTL WM-Align-R">
		<input
			type="checkbox"
			:id="rand"
			class="c-check"
			:value="valueSelected"
			v-model="values"
			@change="changeValue"
		/>
		<label :for="rand">
			<span class="inc"></span>
			<span class="check"></span>
			<span class="box"></span>
			{{ showText }}
		</label>
	</div>
</template>

<script>
export default {
	props: {
		itemValue: { default: null },
		itemSlug: { default: 'id' },
		itemText: { default: null },
		text: { default: " " },
		item: { default: {} },
		color: { default: "Red" },
		value: { type: Array }
	},
	data: function() {
		return {
			IconClass: "WMi-" + this.Icon,
			rand: Math.random(),
			values: this.computedValues(this.value)
		};
	},
	computed: {
		valueSelected() {
			if (typeof this.item == 'object') {
				if (this.itemValue) {
					return this.item[this.itemValue];
				} else {
					return this.item[this.itemSlug];
				}
			} else {
				return this.item;
			}
		},
		showText() {
			if (this.itemText) {
				return this.item[this.itemText];
			}
			return this.text;
		},
	},
	methods: {
		changeValue($event) {
			if (this.value) {
				if ($event.target.checked) {
					if (this.itemValue) {
						this.value.push(this.valueSelected);
					} else {
						this.value.push(this.item);
					}
				} else {
					if (typeof this.item == 'object' && !this.itemValue) {
						var index = this.value.findIndex(
							x => x[this.itemSlug] == this.item[this.itemSlug]
						);
					} else {
						var index = this.value.findIndex(
							x => x == this.valueSelected
						);
					}
					this.value.splice(index, 1);
				}
			}
			this.$emit("change", this.item, $event.target.checked);
		},
		computedValues(value) {
			if (Array.isArray(value)) {
				let newArray = [];
				for (const val of value) {
					if (typeof val == "object") {
						newArray.push(val[this.itemSlug]);
					} else {
						newArray.push(val);
					}
				}
				return newArray;
			} else {
				return value;
			}
		}
	},
	watch: {
		value(value) {
			this.values = this.computedValues(value);
		},
	}
};
</script>
