<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 },
		itemText: { default: null },
		text: { default: " " },
		item: { default: {} },
		color: { default: "Red" },
		value: { type: Array }
	},
	data: function() {
		return {
			IconClass: "WMi-" + this.Icon,
			rand: Math.random()
		};
	},
	computed: {
		valueSelected() {
			if (this.itemValue) {
				return this.item[this.itemValue];
			}
			return this.item;
		},
		showText() {
			if (this.itemText) {
				return this.item[this.itemText];
			}
			return this.text;
		},
		values: {
			get() {
				if (this.itemValue) {
					let newval = [];
					for (const val of this.value) {
                        newval.push(val[this.itemValue]);
                    }
					return newval;
				}
				return this.value;
			},
			set() {}
		}
	},
	methods: {
		changeValue($event) {
			if (this.value) {
				if ($event.target.checked) {
					this.value.push(this.valueSelected);
				} else {
					let index = this.value.findIndex(
						x => x == this.valueSelected
					);
					this.value.splice(index, 1);
				}
			}
			this.$emit("change", this.item, $event.target.checked);
		}
	},
	watch: {
		value(value) {
			if (this.itemValue) {
				this.values = value[this.itemValue];
			} else {
				this.values = value;
			}
		}
	}
};
</script>
