"use strict"; angular.module("vocabulary") .component("categoryHeader", { templateUrl: "/js/redesign-angular/categories/category-header.html", controller: "CategoryHeaderController", bindings:{ categoryName: '<', categoryId: '<', parentCategoryId: '<', onUpdateCategory: '&', onDeleteCategory: '&' } }) .controller("CategoryHeaderController", [ "categoryService", "categoryValidationService", "messageHandler","MessageBox", "$window", function(categoryService, categoryValidationService, messageHandler, MessageBox, $window){ var ctrl = this; this.$onInit = init; ctrl.newCategoryName = ""; ctrl.isEditPending = false; ctrl.isEditAllowed = false; function init() { ctrl.newCategoryName = ctrl.categoryName; if(ctrl.categoryId > 0){ ctrl.isEditAllowed = true; } } ctrl.editCategory = function(){ ctrl.isEditPending= !ctrl.isEditPending; }; ctrl.renameCategory = function(){ ctrl.newCategoryName = ctrl.categoryName; ctrl.closePopover(); ctrl.editCategory(); }; ctrl.setPopover = function (popoverCtrl) { ctrl.popoverCtrl = popoverCtrl; }; ctrl.closePopover = function () { if (ctrl.popoverCtrl) { ctrl.popoverCtrl.close(); } }; ctrl.setFocus = function( elementById){ $window.document.getElementById(elementById).focus(); }; ctrl.deleteCategory = function(){ ctrl.closePopover(); var deleteMessage = "Are you sure you want to delete this category? All lessons currently in this category will be moved to 'Uncategorized'"; MessageBox.show({ message: deleteMessage, responses: [ { subtle: true, label: 'Cancel' }, { id: 'delete', confirm: true, label: 'Delete Category' } ] }).then(function(response) { if (response.id === 'delete') { categoryService.deleteCategory(ctrl.categoryId, ctrl.parentCategoryId).then(function (isDeleted) { if (isDeleted) { var categoryName = ctrl.categoryName; messageHandler.publishError("'" + categoryName + "' has been deleted"); ctrl.onDeleteCategory(); } else { messageHandler.publishError("There was a problem processing your request"); } }).catch(function (reason) { messageHandler.publishError("There was a problem processing your request"); }); } }); }; ctrl.updateCategoryName = function(){ categoryValidationService.validateCategoryUpdate(ctrl.newCategoryName) .then(function(){ categoryService.updateCategoryName(ctrl.newCategoryName, ctrl.categoryId) .then(function (result) { ctrl.categoryName = ctrl.newCategoryName; ctrl.newCategoryName = ""; ctrl.editCategory (); ctrl.onUpdateCategory(); }).catch(function(reason) { messageHandler.publishError("There was a problem with your request"); }); }) .catch(setErrors); }; ctrl.invalidField = function (field) { return field.$invalid && field.$dirty; }; ctrl.resetDupe = function () { ctrl.categoryForm.title.$setValidity("dupe", true); }; ctrl.onEnter = function(keyEvent){ if(keyEvent.which === 13){ ctrl.updateCategoryName(); } }; function setErrors(errors) { ctrl.categoryForm.title.$setDirty(); if (errors.duplicate) { ctrl.categoryForm.title.$setValidity("dupe", false); } } }]);