/**
 *
 */
angular.module("myApp").controller("employeeController", function ($scope, $http, $state) {
    console.log("Employee controller");

    $scope.emp = {
        "username": "",
        "password": "",
        "firstName": "",
        "lastName": "",
        "emailAddress": "",
        "phoneNumber": "",
        "homeTown": "",
        "education": "",
        "department": "",
        "position": ""

    };


    $scope.save = save;


    $scope.currentPage = 1;
    $scope.employeePerPage = 3;
    $scope.maxSize = 5;
    $scope.numberOfPage = numberOfPage;
    $scope.dataHasLoaded = false;

    function numberOfPage() {
        return Math.ceil($scope.employess.length / $scope.employeePerPage);

    };

    function save() {
        console.log($scope.emp);
        $http({
            method: 'POST',
            url: "http://localhost:8081/list_employee/",
            data: $scope.emp
        }).then(function successCallback(response) {
            console.log(response);

        }, function errorCallback(response) {
            console.log(response)
        });
    }

    $scope.updateEmp = updateEmp;

    function updateEmp(emp) {
        console.log('edit');
        $state.go('createEmployee', {emp: emp});

    }

    // HTTP DELETE- delete employee by Id
    // Call: http://localhost:8080/employee/{id}
    $scope.deleteEmp = function (emp) {
        $http({
            method: 'DELETE',
            url: '/employee/' + emp.id
        }).then(function successCallback(response) {
            console.log(response);
            $scope.employess = response.data;
        }, function errorCallback(response) {
            console.log(response)
        });
    };
    // In case of edit
    $scope.edit = function (emp) {
        $scope.emp.username = emp.username;
        $scope.emp.password = emp.password;
        $scope.emp.firstName = emp.firstName;
        $scope.emp.lastName = emp.lastName;
        $scope.emp.emailAddress = emp.emailAddress;
        $scope.emp.phoneNumber = emp.phoneNumber;
        $scope.emp.homeTown = emp.homeTown;
        $scope.emp.education = emp.education;
        $scope.emp.department = emp.department;
        $scope.emp.position = emp.position;
    };


    $http({
        method: 'GET',
        url: "http://localhost:8081/list_employee/"
    }).then(function successCallback(response) {
        console.log(response);

        $scope.employess = response.data;

        $scope.dataHasLoaded = true;

        $scope.$watch('currentPage + numPerPage', function () {
            var begin = (($scope.currentPage - 1) * $scope.employeePerPage),
                end = begin + $scope.employeePerPage;

            $scope.filteredEmployee = $scope.employess.slice(begin, end);
        });
    }, function errorCallback(response) {
        console.log(response)
    });

});





