(function(){ "use strict"; angular.module('shared') .provider('groups', function () { var groups; return { $get: ['$q', 'serverGroups', '_', groupsFactory], setGroups: setGroups, } function groupsFactory($q, serverGroups, _) { initGroups(); return { get: get, add: add, update: update, remove: remove, nameAvailable: nameAvailable, findGroupByName: findGroupByName, findGroupById: findGroupById } function initGroups() { if (angular.isDefined(groups)) { groups.$promise = $q.resolve(groups); } else { groups = serverGroups.query(); } } function indexOfGroupById(group) { var index; for (index = 0; index < groups.length; ++index) { if (groups[index].grouping_id == group.grouping_id) { return index; } } return -1; } function get() { return groups; } function add(group) { return serverGroups.save(group, function (result) { groups.push(result); }); } function update(group) { return serverGroups.update(group, function (result) { var idx = indexOfGroupById(group); if (-1 != idx) { angular.extend(groups[idx], result); } }); } function remove(group) { return serverGroups.remove(group, {id: group.grouping_id}, function () { var idx = indexOfGroupById(group); if (-1 != idx) { group.is_deleted = true; groups.splice(idx, 1); } }); } function findGroupByName(name, exceptGroup) { var searchGroups = exceptGroup === undefined ? groups : _.reject(groups, function (group) { return group == exceptGroup; }); if (name.toUpperCase() === "ALL") { return false; } return _.find(searchGroups, function (group) { return group.grouping_name.toUpperCase() === name.toUpperCase(); }) } function findGroupById(id) { return _.find(groups, function (group) { return group.grouping_id == id; }) } function nameAvailable(name, exceptGroup) { var foundGroup = findGroupByName(name, exceptGroup); return foundGroup == null; } } function setGroups(src) { groups = src; } }) })();