/*global angular*/
(function () {
    angular
        .module('simplAdmin.core')
        .controller('UnitListCtrl', ['unitService', 'translateService', UnitListCtrl]);

    function UnitListCtrl(unitService, translateService) {
        var vm = this;
        vm.tableStateRef = {};
        vm.units = [];
        vm.translate = translateService;

        vm.getUnits = function getUnits(tableState) {
            vm.tableStateRef = tableState;
            vm.isLoading = true;
            unitService.getUnits(tableState).then(function (result) {
                vm.units = result.data.items;
                tableState.pagination.numberOfPages = result.data.numberOfPages;
                tableState.pagination.totalItemCount = result.data.totalRecord;
                vm.isLoading = false;
            });
        };

        vm.update = function (unit) {
            unitService.editUnit(unit)
                .then(function (result) {
                    toastr.success(unit.name + ' has been updated');
                })
                .catch(function (response) {
                    toastr.error(response.data.error);
                });
        };

        vm.deleteUnit = function (unit) {
            bootbox.confirm('Are you sure you want to delete this unit: ' + simplUtil.escapeHtml(unit.name), function (result) {
                if (result) {
                    unitService.deleteUnit(unit)
                        .then(function (result) {
                            vm.getUnits(vm.tableStateRef);
                            toastr.success(unit.name + ' has been deleted');
                        })
                        .catch(function (response) {
                            toastr.error(response.data.error);
                        });
                }
            });
        };
    }
})();
