<template>
	<div class="row col-md-10 col-md-offset-1">
		<div class="col-md-4">
			<h4>UNDIAN CALON ANGGOTA LEMBAGA</h4>
			<hr />
			<ul class="list-group">
				<li class="list-group-item" v-for="position in data.positions">
					<b>{{ position.name }} : </b>
				</li>
				<ul class="list-group">
					<li class="list-group-item" v-for="nominee_id in selected[0].nominee_id">
						<b> - {{ getSelectedNomineeName(nominee_id) }}</b>
					</li>
				</ul>

				<li class="list-group-item">
					<center>
						<button class="btn btn-success" @click="checkUndi()">UNDI</button>
						<!-- <button class="btn btn-default" @click="reset()">Reset</button> -->
					</center>
				</li>
			</ul>
		</div>
		<div class="col-md-8">
			<h4>Senarai Calon</h4>
			<div class="alert alert-warning " role="alert">
				Anda Hanya Boleh Memilih <b> dua (2) Orang Calon</b> Sahaja.
			</div>
			<hr />
			<div class="panel panel-info" v-for="position in data.positions">
				<div class="panel-heading">{{ position.name }}</div>
				<div class="panel-body table-responsive">
					<table class="table table-hover">
						<thead>
							<tr>
								<th></th>
								<th>No. Calon</th>
								<th></th>
								<th>Nama</th>
								<th>Unit</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(nominee, index) in data.nominees" v-if="nominee.position_id == position.id"
								:key="nominee.id">
								<td><input type="checkbox" :id="nominee.id" :disabled="disabledCheckboxes[index]"  @change="vote(position.id, nominee.id)" />
								</td>
								<td>{{ nominee.no_calon }}</td>
								<td><img @click="view(i)" :src="createBase64ImageUrl(nominee.photo)" class="thumbnail"
										style="height: 60px;width: 60px;" />
								</td>
								<td>{{ nominee.name }}</td>
								<td>{{ nominee.unit }}</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>

		<div class="modal" id="vote-modal" tabindex="-2" role="dialog" aria-labelledby="exampleModalLabel"
			aria-hidden="true">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="exampleModalLabel"></h5>
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div class="modal-body">
						<h5>Nota: Sila pastikan anda telah membuat undian dengan betul.</h5>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
						<button type="button" class="btn btn-primary" @click="submit()">Hantar</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
export default {
	created: function () {
		if (this.data.result.length > 0 || this.data.election.status != 2)
			this.$router.push({ name: 'Voter Home' })
		for (var i in this.data.positions) {
			this.selected.push({
				position_id: this.data.positions[i]['id'],
				nominee_id: [],
			});
		}
	},

	data: function () {
		return {
			selected: [],
			name: {},
			selectedNominees: {
			},
			max: 2
		}
	},

	computed: {
		disabledCheckboxes() {
			const selectedNomineeIds = this.selected[0]['nominee_id'];
			return this.data.nominees.map(nominee => {
			return selectedNomineeIds.includes(nominee.id) ? false : this.checkDisabled();
			});
		}
	},

	methods: {
		test: function () {
			console.log('tab');
			this.util.showModal('#vote-modal')
		},
		submit: function () {
			if (this.selected[0]['nominee_id'].length !== this.max) {
				// No selections made
				this.util.notify(`Sila pastikan anda memilih (${this.max}) orang calon.`, 'error');
				return;
			}

			var vm = this;
			this.util.notify('Submitting your vote, please wait...', 'loading');
			console.log(this.selected)
			// Prepare data to send to the server
			let data = {
				vote: this.selected
			};

			// Send a POST request to the server
			axios.post(config.API + 'election/vote', data)
				.then(response => {
					$.notifyClose();
					if (vm.util.showResult(response, 'success')) {
						vm.data.result = response.data.result;
						vm.$router.push({ name: 'Voter Home' });
						$('.modal').modal('hide');
					}
				})
				.catch(error => {
					$.notifyClose();
					vm.util.showResult(error, 'error');
				});
		},

		hasNullVote: function () {
			console.log('null' + this.selectedNominees);
			let selected = this.selectedNominees;
			for (var i in selected)
				if (selected[i]['nominee_id'] == null) {
					this.util.notify('You must vote on all position', 'error');
					return true;
				}
			return false;
		},

		reset: function () {
			let selected = this.selectedNominees;
			for (var i in selected) {
				$('#' + selected[i]['nominee_id']).selected(false);
				selected[i]['nominee_id'] = null;
			}
		},
		vote: function (position_id, nominee_id) {
			
            if (!this.selected[0]['position_id']) {
                this.$set(this.selected[0], position_id, []);
            }
            const index = this.selected[0]['nominee_id'].indexOf(nominee_id);
            if (index === -1) {
                // Nominee not found, add it
                if (this.selected[0]['nominee_id'].length < this.max) {
                    this.selected[0]['nominee_id'].push(nominee_id);
                } else {
                    // Display warning message if more than 2 nominees are selected
                    this.util.notify(`Boleh mengundi (${this.max}) calon sahaja!`, 'warning');
					return;
                }
            } else {
                // Nominee found, remove it
                this.selected[0]['nominee_id'].splice(index, 1);
            }
        },

		getSelectedNomineeName: function (id) {
			return this.getNominee(id);
		},

		getName: function (id) {
			let positions = this.data.positions;
			let selected = this.selected;

			for (var i in selected)
				if (selected[i]['position_id'] == id)
					return this.getNominee(selected[i]['nominee_id']);
			return '';
		},

		getNominee: function (id) {
			let positions = this.data.positions;
			let nominees = this.data.nominees;
			for (var i in nominees)
				if (nominees[i]['id'] == id) return nominees[i].name;
			return '';
		},

		// getNominee: function (id) {
		// 	let nominees = this.data.nominees;
		// 	for (var i in nominees)
		// 		if (nominees[i]['id'] == id) return nominees[i]['name'];
		// },

		getPartylist: function (id) {
			let partylists = this.data.partylists;
			for (var i in partylists)
				if (partylists[i]['id'] == id) return partylists[i]['name'];
			return 'No Partylist';
		},

		view: function (index) {
			this.x = this.data.nominees[index];
			this.util.showModal('#nominee-information-modal');
		},

		createBase64ImageUrl: function (base64ImageData) {
			return "data:image/png;base64," + base64ImageData;
		},

		checkUndi: function(){
			if(this.selected[0]['nominee_id'].length <= 1){
				this.util.notify('Sila pastikan anda memilih (2) orang calon.', 'error');
			}else{
				this.util.showModal('#vote-modal');
			}
			return;
		},

		checkDisabled: function(){
			if(this.selected[0]['nominee_id'].length >= this.max){
				return true;
			}
		}

		// uncheck: function (checkedName) {
		// 	this.checkedName = this.checkedNames.filter(name => name !== checkedName);
		// }
	}
}
</script>
