<template>
	<div class="panel panel-default">
		<div class="panel-body">

			<div class="form-group">
				<router-link :to="{ name: 'Add Account' }" class="btn btn-success">
					<i class="fa fa-plus"></i> Tambah Akaun Pengguna</router-link>
				<button class="btn btn-default" @click="refreshAdmin()" :disabled="!canViewAdminList">
					<i class="fa fa-refresh"></i> Refresh</button>
			</div>

			<div v-if="!canViewAdminList" class="alert alert-warning" style="margin-bottom:12px;">
				Akses ditolak: Pengurusan akaun hanya untuk <b>Main Admin</b> (id=1). Jika sedang impersonate, sila
				<b>Kembali Akaun Asal</b>.
			</div>

			<admin-data-table :headers="adminTableHeaders" :items="adminItems" :loading="loading"
				:show-pagination="true" :exportable="true" export-file-name="admins" :items-per-page="25"
				:show-index="true" index-title="Bil." empty-text="Tiada akaun admin">
				<template v-slot:item-impersonate="{ item }">
					<button class="btn btn-primary btn-sm" @click="openImpersonate(item)"
						:disabled="!canImpersonate(item)">
						<i class="fa fa-user-secret"></i> Impersonate
					</button>
				</template>
				<template v-slot:item-delete="{ item }">
					<button class="btn btn-danger btn-sm" @click="deleteAdmin(item.id)">
						<i class="fa fa-trash"></i> Padam
					</button>
				</template>
			</admin-data-table>
		</div>
		<modal id="delete-admin-modal">
			<modal-header>Delete Admin</modal-header>
			<modal-body>
				<h3>Are you sure to delete this admin?</h3>
			</modal-body>
			<modal-footer>
				<button @click="deleteAdmin()" class="btn btn-danger">Padam</button>
				<button @click="util.hideModal('#delete-admin-modal')" class="btn btn-default">Batal</button>
			</modal-footer>
		</modal>
		<modal id="impersonate-admin-modal">
			<modal-header>Menyamar Admin</modal-header>
			<modal-body>
				<h4 v-if="impersonateTarget && impersonateTarget.email">
					Menyamar <b>{{ impersonateTarget.email }}</b> ?
				</h4>
				<p class="text-muted" style="margin-bottom:0;">
					Anda akan log masuk sebagai akaun tersebut.
				</p>
			</modal-body>
			<modal-footer>
				<button @click="startImpersonate()" class="btn btn-primary">Menyamar</button>
				<button @click="util.hideModal('#impersonate-admin-modal')" class="btn btn-default">Batal</button>
			</modal-footer>
		</modal>
	</div>
</template>

<script>
import AdminDataTable from '../../../AdminDataTable.vue';

export default {
	components: { AdminDataTable },

	data: () => ({
		id: 0,
		impersonateTarget: null,
		loading: false,
		adminTableHeaders: [
			{ title: 'Nama', key: 'name', sortable: true },
			{ title: 'Email', key: 'email', sortable: true },
			{ title: 'Menyamar', key: 'impersonate', sortable: false, exportValue: function () { return ''; } },
			{ title: 'Padam', key: 'delete', sortable: false, exportValue: function () { return ''; } },
		]
	}),

	computed: {
		canViewAdminList: function () {
			try {
				if (!this.data || !this.data.user) return false;
				if (Number(this.data.user.id) !== 1) return false;
				return localStorage.getItem('is_impersonating') !== '1';
			} catch (e) {
				return false;
			}
		},
		adminItems: function () {
			var a = this.data && this.data.admins;
			if (Array.isArray(a)) return a;
			if (a && Array.isArray(a.data)) return a.data;
			return [];
		}
	},

	created: function () {
		if (this.canViewAdminList) {
			this.refreshAdmin();
		} else {
			this.loading = false;
		}
	},

	methods: {
		canImpersonate: function (admin) {
			// Backend currently limits to main admin (id=1) and blocks impersonating id=1.
			try {
				if (!this.data || !this.data.user) return false;
				if (Number(this.data.user.id) !== 1) return false;
				if (!admin || admin.id === undefined || admin.id === null) return false;
				return Number(admin.id) !== 1;
			} catch (e) {
				return false;
			}
		},

		openImpersonate: function (admin) {
			this.impersonateTarget = admin;
			if (this.util && this.util.showModal) {
				this.util.showModal('#impersonate-admin-modal');
			}
		},

		startImpersonate: function () {
			var vm = this;
			if (!vm.impersonateTarget || !vm.impersonateTarget.id) return;
			vm.util.hideModal('#impersonate-admin-modal');
			vm.util.notify('Menyamar admin', 'loading');

			axios.post(config.API + 'admin/impersonate', { user_id: vm.impersonateTarget.id })
				.then(function (response) {
					$.notifyClose();
					if (!response || !response.data || response.data.status !== 'success') {
						vm.util.showResult(response, 'error');
						return;
					}

					// Swap admin token + user in local state.
					var token = response.data.token;
					if (token) {
						localStorage['Access Token'] = 'Bearer ' + token;
						localStorage.setItem('is_impersonating', '1');
						if (vm.util && vm.util.setAuthorization) vm.util.setAuthorization();
					}
					if (response.data.user) {
						vm.data.user = response.data.user;
						if (response.data.user.role !== undefined && response.data.user.role !== null) {
							localStorage.setItem('admin_role', String(response.data.user.role));
						}
					}

					vm.util.notify('Menyamar berjaya', 'success');
					// Ensure admin shell is refreshed (nav header shows new user)
					if (vm.$router) vm.$router.go(0);
				})
				.catch(function (error) {
					$.notifyClose();
					vm.util.showResult(error, 'error');
				});
		},

		deleteAdmin: function () {
			this.util.hideModal('#delete-admin-modal');
			this.util.notify('Memadam admin', 'loading');
			var vm = this;
			axios.delete(config.API + 'admin/' + this.id)
				.then(response => {
					$.notifyClose();
					if (vm.util.showResult(response, 'success'))
						vm.refreshAdmin();
				})
				.catch(error => {
					$.notifyClose();
					vm.util.showResult(error, 'error');
				})
		},

		refreshAdmin: function () {
			var vm = this;
			if (!vm.canViewAdminList) {
				return;
			}
			vm.loading = true;
			this.util.notify('Mengemaskini admin', 'loading');
			axios.get(config.API + 'admin')
				.then(response => {
					$.notifyClose();
					if (response.data.status == 'failed')
						vm.util.showResult(response, 'success');
					else
						vm.data.admins = response.data;
				})
				.catch(error => {
					$.notifyClose();
					vm.util.showResult(error, 'error');
				})
				.finally(function () {
					vm.loading = false;
				});
		}
	}
}
</script>