(function() { "use strict"; angular.module("raz") .service("autoAssignedGoalSets", ["autoAssignedGoalSetsApi", "$q", "studentList", "_", function (autoAssignedGoalSetsApi, $q, studentList, _) { var autoAssignedStudentsBySet = []; var students = []; function getAutoAssignedStudentsForGoalSet(categoryId) { if (autoAssignedStudentsBySet[categoryId]) { var deferred = $q.defer(); deferred.resolve(autoAssignedStudentsBySet[categoryId]); return deferred.promise; } else { return studentList.get().$promise .then(function(results) { students = results; return autoAssignedGoalSetsApi.getAutoAssignedStudentsForGoalSet(categoryId) .then(function(data) { autoAssignedStudentsBySet[categoryId] = populateStudentNames(data); return autoAssignedStudentsBySet[categoryId]; }) .catch(function(error) { console.log(error); }) }) .catch(function(error) { console.log(error); }) } } function populateStudentNames(goalSetStudents) { var newStudents = []; goalSetStudents.each(function(student) { if (student.hasOwnProperty('student_id')) { var studentName = getStudentName(student['student_id']); if (studentName !== null) { newStudents.push({student_id: student['student_id'], student_name: studentName}); } } }) return newStudents; } function getStudentName(student_id) { var foundStudent = _.find(students, function (student) { return student.student_id == student_id; }); if (foundStudent == null) { return null; } return foundStudent.student_name; } return { getAutoAssignedStudentsForGoalSet: getAutoAssignedStudentsForGoalSet }; }]); })();