/*
 * Edited by:     Nermin Jukan, 63150367
 * Date:          21. 05. 2018
 * Modifications: Added a delete users function on lines 31-40.
 */

'use strict';

angular
	.module('sloDialectsAdmin')
	.component('users', {
		templateUrl: 'components/users/users.template.html',
		controller: ['$http', '$location', 'AuthenticationService',
            function UsersController($http, $location, AuthenticationService) {

			var vm = this;
			vm.go = go;

			vm.user = AuthenticationService.GetCredentials();
			vm.user.admin = isAdmin(vm.user.username);


			//vm.users = [];

			getUsers();

			function isAdmin(username) {
			    //console.log(username);
                $http.post('../api/admin/', {username: username}).then(function (result) {
                    //console.log(result.data);
                    vm.user.admin = result.data.is_admin;
                    //console.log(vm.user.admin);
                }, function (error) {
                    console.log('Error retrieving admin rights', error);
                });
            }

			// TODO
			function getUsers() {
                $http.get('../api/users').then(function (result) {
                    vm.users = result.data;
                }, function (error) {
                    console.log('Error getting users', error);
                });
            }

            vm.delete = function (id, name) {
                if (confirm("Ali ste prepričani, da želite izbrisati uporabnika " + name + "?")) {
                    $http.delete('../api/users/'+id).then(function(result){
                        console.log(result.data);
                        getUsers();
                    }, function(error){
                        console.log('Error deleting entry:', error);
                    });
                }
            };

			function go(path) {
				$location.path(path);
			}



		}]
	});