<template>
	<div class="panel panel-default">
		<div class="panel-body">
			<button class="btn btn-success" @click="refreshVoter()">
				<i class="fa fa-refresh"></i> Refresh Voter
			</button>

			<div class="table-responsive">
				<table class="table table-hover">
					<thead>
						<tr>
							<th>Nama Anggota</th>
							<th>No. Kad Pengenalan</th>
							<th>No. Anggota</th>
							<th>Unit</th>
							<th>Kehadiran</th>
							<th>Tarikh/Masa</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="(voter, i) in data.voters.data">
							<td>{{ voter.name }}</td>
							<td>{{ voter.no_kp }}</td>
							<td>{{ voter.no_anggota }}</td>
							<td>{{ voter.unit }}</td>
							<td>{{ getKehadiranString(voter.kehadiran) }}</td>
							<td>{{ voter.updated_at }}</td>
						</tr>
						<!-- <tr v-if="data.elections.length < 1">
							<td colspan="5">No elections yet</td>
						</tr> -->
					</tbody>
				</table>
			</div>

			<ul class="pagination" v-if="pages.length > 1">
				<router-link tag="li" v-for="page in pages" :key="page['pages']" :to="{ query: { page: page['page'] } }"
					:class="{ 'active': current_page == page['page'] }" exact>
					<a href="#">{{ page['page'] }}</a>
				</router-link>
			</ul>
		</div>
	</div>
</template>

<script>
export default {
	data: function () {
		return {
			id: 0
		}
	},

	created: function () {
		this.refreshVoter();
	},

	methods: {
		search: function () {

		},

		refreshVoter: function () {
			var vm = this;
			this.util.notify('Refreshing Voter', 'loading');
			axios.get(config.API + 'voter?page=' + this.current_page)
				.then(response => {
					console.log(response)
					$.notifyClose();
					vm.data.voters = response.data;
				})
				.catch(error => {
					$.notifyClose();
					vm.util.showResult(error);
				})
		},

		getKehadiranString(kehadiran) {
			// Map integer values to corresponding string representations
			switch (kehadiran) {
				case 1:
					return 'Fizikal';
				case 2:
					return 'Maya';
				default:
					return '-';
			}
		}

	},

	watch: {
		'$route.query.page': function () {
			$.notifyClose();
			this.refreshVoter();
		}
	},

	computed: {
		pages: function () {
			var pages = [];
			if (this.data.voters.last_page)
				for (var i = 1; i <= this.data.voters.last_page; i++) {
					let x = {};
					x['page'] = i;
					pages.push(x);
				}
			return pages;
		},

		current_page: function () {
			return this.$route.query.page ? this.$route.query.page : 1;
		}
	}
}
</script>