Passed
Push — master ( 71fe99...f3b0ea )
by
unknown
09:06
created

myems-admin/app/controllers/settings/space/spacecommand.controller.js   B

Complexity

Total Complexity 44
Complexity/F 2

Size

Lines of Code 245
Function Count 22

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 44
eloc 173
mnd 22
bc 22
fnc 22
dl 0
loc 245
rs 8.8798
bpm 1
cpm 2
noi 2
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like myems-admin/app/controllers/settings/space/spacecommand.controller.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
'use strict';
2
3
app.controller('SpaceCommandController', function(
4
    $scope,
5
    $window,
6
    $timeout,
7
    $translate,
8
    SpaceService,
9
    CommandService,
10
    SpaceCommandService, toaster,SweetAlert) {
11
    $scope.spaces = [];
12
    $scope.currentSpaceID = 1;
13
    $scope.commands = [];
14
    $scope.spacecommands = [];
15
    $scope.cur_user = JSON.parse($window.localStorage.getItem("myems_admin_ui_current_user"));
16
    $scope.isLoadingCommands = false;
17
    $scope.tabInitialized = false;
18
    $scope.isSpaceSelected = false;
19
20
    $scope.getAllSpaces = function() {
21
    let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
22
    SpaceService.getAllSpaces(headers, function (response) {
23
      if (angular.isDefined(response.status) && response.status === 200) {
24
        $scope.spaces = response.data;
25
      } else {
26
        $scope.spaces = [];
27
      }
28
      //create space tree
29
      var treedata = {'core': {'data': [], "multiple" : false,}, "plugins" : [ "wholerow" ]};
30
      for(var i=0; i < $scope.spaces.length; i++) {
31
          if ($scope.spaces[i].id == 1) {
32
            var node = {"id": $scope.spaces[i].id.toString(),
33
                                "parent": '#',
34
                                "text": $scope.spaces[i].name,
35
                                "state": {  'opened' : true,  'selected' : false },
36
                               };
37
          } else {
38
              var node = {"id": $scope.spaces[i].id.toString(),
39
                                  "parent": $scope.spaces[i].parent_space.id.toString(),
40
                                  "text": $scope.spaces[i].name,
41
                                 };
42
          };
43
          treedata['core']['data'].push(node);
44
      }
45
46
      angular.element(spacetreewithcommand).jstree(treedata);
47
      //space tree selected changed event handler
48
      angular.element(spacetreewithcommand).on("changed.jstree", function (e, data) {
49
          if (data.selected && data.selected.length > 0) {
50
              $scope.currentSpaceID = parseInt(data.selected[0]);
51
              $scope.isSpaceSelected = true;
52
              $scope.getCommandsBySpaceID($scope.currentSpaceID);
53
          } else {
54
              $scope.isSpaceSelected = false;
55
              $scope.spacecommands = [];
56
          }
57
          if (!$scope.$$phase && !$scope.$root.$$phase) {
58
              $scope.$apply();
59
          }
60
      });
61
    });
62
    };
63
64
	$scope.getCommandsBySpaceID = function(id) {
65
	if ($scope.isLoadingCommands) return;
66
    $scope.isLoadingCommands = true;
67
    $scope.spacecommands=[];
68
    let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
69
    SpaceCommandService.getCommandsBySpaceID(id, headers, function (response) {
70
                    $scope.isLoadingCommands = false;
71
      				if (angular.isDefined(response.status) && response.status === 200) {
72
      					$scope.spacecommands = response.data;
73
      				} else {
74
                $scope.spacecommands=[];
75
              }
76
    			});
77
		};
78
79
	$scope.getAllCommands = function() {
80
    let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
81
		CommandService.getAllCommands(headers, function (response) {
82
			if (angular.isDefined(response.status) && response.status === 200) {
83
				$scope.commands = response.data;
84
			} else {
85
				$scope.commands = [];
86
			}
87
		});
88
	};
89
90
	$scope.pairCommand=function(dragEl,dropEl){
91
		var commandid=angular.element('#'+dragEl).scope().command.id;
92
		var spaceid=angular.element(spacetreewithcommand).jstree(true).get_top_selected();
93
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
94
		SpaceCommandService.addPair(spaceid,commandid, headers, function (response){
95
			if (angular.isDefined(response.status) && response.status === 201) {
96
					toaster.pop({
97
						type: "success",
98
						title: $translate.instant("TOASTER.SUCCESS_TITLE"),
99
						body: $translate.instant("TOASTER.BIND_COMMAND_SUCCESS"),
100
						showCloseButton: true,
101
					});
102
					$scope.getCommandsBySpaceID(spaceid);
103
				} else {
104
          toaster.pop({
105
              type: "error",
106
              title: $translate.instant(response.data.title),
107
              body: $translate.instant(response.data.description),
108
              showCloseButton: true,
109
          });
110
				}
111
		});
112
	};
113
114
	$scope.deleteCommandPair=function(dragEl,dropEl){
115
		if(angular.element('#'+dragEl).hasClass('source')){
116
			return;
117
        }
118
        var spacecommandid = angular.element('#' + dragEl).scope().spacecommand.id;
119
        var spaceid = angular.element(spacetreewithcommand).jstree(true).get_top_selected();
120
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
121
        SpaceCommandService.deletePair(spaceid, spacecommandid, headers, function (response) {
122
            if (angular.isDefined(response.status) && response.status === 204) {
123
                toaster.pop({
124
                    type: "success",
125
                    title: $translate.instant("TOASTER.SUCCESS_TITLE"),
126
                    body: $translate.instant("TOASTER.UNBIND_COMMAND_SUCCESS"),
127
                    showCloseButton: true,
128
                });
129
                $scope.getCommandsBySpaceID(spaceid);
130
            } else {
131
                toaster.pop({
132
                    type: "error",
133
                    title: $translate.instant(response.data.title),
134
                    body: $translate.instant(response.data.description),
135
                    showCloseButton: true,
136
                });
137
            }
138
		});
139
	};
140
141
    $scope.initTab = function() {
142
        if (!$scope.tabInitialized) {
143
            $scope.tabInitialized = true;
144
            $scope.getAllSpaces();
145
            $scope.getAllCommands();
146
        }
147
    };
148
149
    $scope.$on('space.tabSelected', function(event, tabIndex) {
150
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { COMMAND: 10 };
151
        if (tabIndex === TAB_INDEXES.COMMAND && !$scope.tabInitialized) {
152
            $scope.initTab();
153
        }
154
    });
155
156
    $timeout(function() {
157
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { COMMAND: 10 };
158
        if ($scope.$parent && $scope.$parent.activeTabIndex === TAB_INDEXES.COMMAND && !$scope.tabInitialized) {
159
            $scope.initTab();
160
        }
161
    }, 0);
162
163
  $scope.refreshSpaceTree = function() {
164
    let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
165
    SpaceService.getAllSpaces(headers, function (response) {
166
      if (angular.isDefined(response.status) && response.status === 200) {
167
        $scope.spaces = response.data;
168
      } else {
169
        $scope.spaces = [];
170
      }
171
      //create space tree
172
      var treedata = {'core': {'data': [], "multiple" : false,}, "plugins" : [ "wholerow" ]};
173
      for(var i=0; i < $scope.spaces.length; i++) {
174
          if ($scope.spaces[i].id == 1) {
175
            var node = {"id": $scope.spaces[i].id.toString(),
176
                                "parent": '#',
177
                                "text": $scope.spaces[i].name,
178
                                "state": {  'opened' : true,  'selected' : false },
179
                               };
180
          } else {
181
              var node = {"id": $scope.spaces[i].id.toString(),
182
                                  "parent": $scope.spaces[i].parent_space.id.toString(),
183
                                  "text": $scope.spaces[i].name,
184
                                 };
185
          };
186
          treedata['core']['data'].push(node);
187
      }
188
189
      angular.element(spacetreewithcommand).jstree(true).settings.core.data = treedata['core']['data'];
190
      angular.element(spacetreewithcommand).jstree(true).refresh();
191
      // Reset selection state after tree refresh
192
      $scope.isSpaceSelected = false;
193
      $scope.spacecommands = [];
194
      if (!$scope.$$phase && !$scope.$root.$$phase) {
195
          $scope.$apply();
196
      }
197
    });
198
  };
199
200
	$scope.$on('handleBroadcastSpaceChanged', function(event) {
201
    $scope.spacecommands = [];
202
    $scope.refreshSpaceTree();
203
	});
204
205
    // Listen for disabled drop events to show warning
206
    // Only show warning if this tab is currently active
207
    $scope.$on('HJC-DROP-DISABLED', function(event) {
208
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { COMMAND: 10 };
209
        if ($scope.$parent && $scope.$parent.activeTabIndex === TAB_INDEXES.COMMAND) {
210
            $timeout(function() {
211
                try {
212
                    toaster.pop({
213
                        type: "warning",
214
                        body: $translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"),
215
                        showCloseButton: true,
216
                    });
217
                } catch(err) {
218
                    console.error('Error showing toaster:', err);
219
                    alert($translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"));
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
220
                }
221
            }, 0);
222
        }
223
    });
224
225
    // Listen for disabled drag events to show warning
226
    // Only show warning if this tab is currently active
227
    $scope.$on('HJC-DRAG-DISABLED', function(event) {
228
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { COMMAND: 10 };
229
        if ($scope.$parent && $scope.$parent.activeTabIndex === TAB_INDEXES.COMMAND) {
230
            $timeout(function() {
231
                try {
232
                    toaster.pop({
233
                        type: "warning",
234
                        body: $translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"),
235
                        showCloseButton: true,
236
                    });
237
                } catch(err) {
238
                    console.error('Error showing toaster:', err);
239
                    alert($translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"));
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
240
                }
241
            }, 0);
242
        }
243
    });
244
245
});
246