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

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

Complexity

Total Complexity 44
Complexity/F 2

Size

Lines of Code 243
Function Count 22

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

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