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

    function UnitFormCtrl($state, $stateParams, unitService, translateService) {
        var vm = this;
        vm.translate = translateService;
        vm.unit = {};
        vm.unitId = $stateParams.id;
        vm.isEditMode = vm.unitId;


        vm.save = function save() {
            var promise;
            if (vm.isEditMode) {
                promise = unitService.editUnit(vm.unit);
            } else {
                promise = unitService.createUnit(vm.unit);
            }

            promise
                .then(function (result) {
                    $state.go('units');
                })
                .catch(function (response) {
                    var error = response.data;
                    vm.validationErrors = [];
                    if (error && angular.isObject(error)) {
                        for (var key in error) {
                            vm.validationErrors.push(error[key][0]);
                        }
                    } else { 
                        vm.validationErrors.push(translateService.get('Could not add unit.'));
                    }
                });
        };

        function init() {
            if (vm.isEditMode) {
                unitService.getUnit(vm.unitId).then(function (result) {
                    vm.unit = result.data;
                });
            }
        }

        init();
    }
})();
