Yangman - Params admin
[dlux.git] / modules / yangman-resources / src / main / resources / yangman / controllers / requests-list.controller.js
1 define([
2     'app/yangman/controllers/save-req-dialog.controller',
3     'app/yangman/controllers/edit-collection-dialog.controller',
4     'app/yangman/services/handle-file.services',
5 ], function (SaveReqDialogCtrl, EditCollectionDialogCtrl) {
6     'use strict';
7
8     angular.module('app.yangman').controller('RequestsListCtrl', RequestsListCtrl);
9
10     RequestsListCtrl.$inject = [
11         '$filter', '$mdDialog', '$scope', 'HandleFileService', 'PathUtilsService', 'RequestsService',
12     ];
13
14     function RequestsListCtrl($filter, $mdDialog, $scope, HandleFileService, PathUtilsService, RequestsService) {
15         var vm = this;
16
17         vm.collectionList = RequestsService.createEmptyCollectionList('yangman_collectionsList', vm.getApiCallback);
18         vm.mainList = null;
19         vm.requestList = RequestsService.createEmptyHistoryList('yangman_requestsList', vm.getApiCallback);
20         vm.search = '';
21         vm.collectionsSortAsc = true;
22
23         vm.clearFilter = clearFilter;
24         vm.filterReq = filterReq;
25         vm.filterCol = filterCol;
26         vm.filterColName = filterColName;
27         vm.colMatchingReqsCount = colMatchingReqsCount;
28         vm.downloadCollection = downloadCollection;
29         vm.fakeFilter = fakeFilter;
30         vm.getApiCallback = getApiCallback;
31         vm.loadRequests = loadRequests;
32         vm.toggleCollectionsSort = toggleCollectionsSort;
33         vm.selectRequest = selectRequest;
34
35         vm.showDgDeleteCollection = showDgDeleteCollection;
36         vm.showDgDeleteRequests = showDgDeleteRequests;
37         vm.showDgEditCollection = showDgEditCollection;
38         vm.readCollectionFromFile = readCollectionFromFile;
39         vm.showDgSaveReq = showDgSaveReq;
40
41         vm.showData = showData;
42         vm.useAsMainList = useAsMainList;
43
44         $scope.$on('YANGMAN_REFRESH_HISTORY', loadHistoryRequests);
45         $scope.$on('YANGMAN_REFRESH_COLLECTIONS', loadCollectionRequest);
46
47         loadRequests();
48
49         /**
50          * Clear value of input file used to import collection
51          */
52         function clearFileInputValue(){
53             angular.element(document).find('#importCollection').val('');
54         }
55
56         /**
57          * Importing collection from a file
58          * todo: error handling - msgs for user
59          * @param $fileContent
60          */
61         function readCollectionFromFile($fileContent) {
62             var data = $fileContent,
63                 checkArray = ['sentData',
64                     'receivedData',
65                     'path',
66                     'collection',
67                     'parametrizedPath',
68                     'method',
69                     'status',
70                     'name',
71                 ];
72
73             if (data && RequestsService.validateFile(data, checkArray)){
74                 try {
75                     vm.collectionList.loadListFromFile(data);
76                     vm.collectionList.saveToStorage();
77                     clearFileInputValue();
78                 }
79                 catch (e) {
80                     clearFileInputValue();
81                     console.error('DataStorage error:', e);
82                 }
83             }
84             else {
85                 clearFileInputValue();
86             }
87         }
88
89         function toggleCollectionsSort() {
90             vm.collectionsSortAsc = !vm.collectionsSortAsc;
91         }
92
93         /**
94          * Export collection to json file
95          * @param {Collection} collection
96          */
97         function downloadCollection(collection) {
98
99             var cListJSON = vm.collectionList.getCollectionInJSON(collection.name);
100
101             HandleFileService.downloadFile(collection.name + '.json', cListJSON, 'json', 'charset=utf-8',
102                 function (){},
103                 function (e){
104                     console.error('ExportCollection error:', e);
105                 }
106             );
107         }
108
109
110         /**
111          * Show current reqObj sent data in right panel section
112          * @param reqObj
113          * @param dataType
114          */
115         function showData(reqObj, dataType) {
116             $scope.setRequestToShow(reqObj, dataType);
117             $scope.setRightPanelSection('req-data');
118             $scope.broadcastFromRoot('YANGMAN_REFRESH_CM_DATA');
119         }
120
121         /**
122          * Clear current ctrl search value
123          */
124         function clearFilter(){
125             vm.search = '';
126         }
127
128         /**
129          * Dialog for deleting either selected requests or reqObj
130          *
131          * @param ev
132          * @param reqObj
133          */
134         function showDgDeleteRequests(ev, reqObj){
135             var confirm = $mdDialog.confirm()
136                 .title($filter('translate')('YANGMAN_DELETE_REQ_CONFIRM_TITLE'))
137                 .textContent($filter('translate')('YANGMAN_DELETE_REQ_CONFIRM_TEXT'))
138                 .ariaLabel($filter('translate')('YANGMAN_DELETE_REQ_CONFIRM_TITLE'))
139                 .targetEvent(ev)
140                 .ok($filter('translate')('YANGMAN_OK'))
141                 .cancel($filter('translate')('YANGMAN_CANCEL'));
142
143             $mdDialog.show(confirm).then(function (){
144                 if (reqObj){
145                     vm.mainList.deleteRequestItem(reqObj);
146                 }
147                 else {
148                     vm.mainList.selectedRequests.forEach(function (elem){
149                         vm.mainList.deleteRequestItem(elem);
150                     });
151                 }
152                 vm.mainList.saveToStorage();
153                 loadRequests();
154             });
155         }
156
157
158         /**
159          * Dialog for delete collection
160          * @param ev
161          * @param collObj
162          */
163         function showDgDeleteCollection(ev, collObj){
164             var confirm = $mdDialog.confirm()
165                 .title($filter('translate')('YANGMAN_DELETE_COL_CONFIRM_TITLE'))
166                 .textContent($filter('translate')('YANGMAN_DELETE_COL_CONFIRM_TEXT'))
167                 .ariaLabel($filter('translate')('YANGMAN_DELETE_COL_CONFIRM_TITLE'))
168                 .targetEvent(ev)
169                 .ok($filter('translate')('YANGMAN_OK'))
170                 .cancel($filter('translate')('YANGMAN_CANCEL'));
171
172             $mdDialog.show(confirm).then(function (){
173                 vm.collectionList.deleteCollection(collObj);
174                 vm.collectionList.saveToStorage();
175                 $scope.broadcastFromRoot('YANGMAN_REFRESH_COLLECTIONS');
176             });
177         }
178
179         /**
180          * Check if reqObj matches current search value
181          * @param reqObj
182          * @returns {boolean}
183          */
184         function filterReq(reqObj){
185             return reqObj.path.indexOf(vm.search) !== -1;
186         }
187
188         /**
189          * Check if collection name matches current search value or any collection req matches
190          * @param colObj
191          */
192         function filterCol(colObj){
193             return filterColName(colObj) || colObj.data.some(filterReq);
194         }
195
196         /**
197          * Get count of requests matching filter in collection colObj
198          * @param colObj
199          * @returns {*}
200          */
201         function colMatchingReqsCount(colObj){
202             return colObj.data.filter(vm.filterReq).length;
203         }
204
205         /**
206          * Check if collection name matches current filter
207          * @param colObj
208          * @returns {boolean}
209          */
210         function filterColName(colObj){
211             return colObj.name.indexOf(vm.search) !== -1;
212         }
213
214         /**
215          * Returns true
216          * @returns {boolean}
217          */
218         function fakeFilter(){
219             return true;
220         }
221
222         /**
223          * Show dialog for saving reqObj to collection (used for duplicate req too)
224          * @param ev
225          * @param reqObj
226          * @param duplicate
227          */
228         function showDgSaveReq(ev, reqObj, duplicate){
229
230             $mdDialog.show({
231                 controller: SaveReqDialogCtrl,
232                 controllerAs: 'dialog',
233                 templateUrl: $scope.globalViewPath + 'leftpanel/save-req-dialog.tpl.html',
234                 parent: angular.element('#yangmanModule'),
235                 targetEvent: ev,
236                 clickOutsideToClose: true,
237                 locals: {
238                     requests: reqObj ? [reqObj] : vm.requestList.selectedRequests,
239                     collectionNames: vm.collectionList.getCollectionNames(),
240                     duplicate: duplicate || false,
241                 },
242             }).then(saveRequests);
243         }
244
245         /**
246          * Add each request from requests array to collectionList and save
247          * @param requests
248          */
249         function saveRequests(requests){
250             requests.forEach(function (reqObj){
251                 vm.collectionList.addRequestToList(reqObj);
252                 vm.collectionList.saveToStorage();
253                 $scope.broadcastFromRoot('YANGMAN_REFRESH_COLLECTIONS');
254             });
255         }
256
257
258         /**
259          * Dialog for editing collection name (used for duplicating collection too)
260          * @param ev
261          * @param collection
262          * @param {boolean} duplicate
263          */
264         function showDgEditCollection(ev, collection, duplicate){
265             $mdDialog.show({
266                 controller: EditCollectionDialogCtrl,
267                 controllerAs: 'dialog',
268                 templateUrl: $scope.globalViewPath + 'leftpanel/edit-collection-dialog.tpl.html',
269                 parent: angular.element('#yangmanModule'),
270                 targetEvent: ev,
271                 clickOutsideToClose: true,
272                 locals: {
273                     collection: collection,
274                     allCollections: vm.collectionList.collections,
275                     duplicate: duplicate,
276                 },
277             }).then(duplicate ? duplicateCollection : changeCollectionName);
278         }
279
280         /**
281          * Rename collection
282          * @param {array} names 0. element is old name, 1. element is new name
283          */
284         function changeCollectionName(names){
285             vm.collectionList.renameCollection(names[0], names[1]);
286             vm.collectionList.saveToStorage();
287             $scope.broadcastFromRoot('YANGMAN_REFRESH_COLLECTIONS');
288         }
289
290         /**
291          * Create collection duplicate and save
292          * @param {array} names 0. element is old name, 1. element is new name
293          */
294         function duplicateCollection(names){
295             vm.collectionList.duplicateCollection(names[0], names[1]);
296             vm.collectionList.saveToStorage();
297             $scope.broadcastFromRoot('YANGMAN_REFRESH_COLLECTIONS');
298         }
299
300
301
302         /**
303          *
304          * @param list collectionList or requestList object
305          */
306         function useAsMainList(list){
307             vm.mainList = list;
308         }
309
310         /**
311          * Loading history request and grouping by date
312          */
313         function loadHistoryRequests(){
314             vm.requestList.loadListFromStorage();
315             vm.requestList.groupListByDate();
316         }
317
318         /**
319          * Loading collections
320          */
321         function loadCollectionRequest(){
322             vm.collectionList.loadListFromStorage();
323         }
324
325         /**
326          * Loading both history and collections reqs
327          */
328         function loadRequests(){
329             loadHistoryRequests();
330             loadCollectionRequest();
331         }
332
333         /**
334          * Request in list selection
335          * For history reqs it is possible multiselect, thats why event.ctrlKey is used
336          * @param event
337          * @param requestObj
338          */
339         function selectRequest(event, requestObj){
340             vm.mainList.toggleReqSelection(!event.ctrlKey, requestObj);
341             $scope.setHistoryReqsSelected(vm.requestList.selectedRequests.length > 0);
342         }
343
344         /**
345          *
346          * @param pathString
347          * @returns {*}
348          */
349         function getApiCallback(pathString) {
350             var snp = PathUtilsService.getStorageAndNormalizedPath(pathString),
351             // if the path is for mountpoint then get the path to treedata structure
352                 mpSearchPath = MountPointsConnectorService.alterMpPath(pathString),
353                 apiIndexes = PathUtilsService.searchNodeByPath(mpSearchPath, $scope.treeApis, $scope.treeRows),
354                 selApi = apiIndexes ? $scope.apis[apiIndexes.indexApi] : null,
355                 selSubApi = selApi ? selApi.subApis[apiIndexes.indexSubApi] : null,
356                 copiedApi = selSubApi ?
357                     selSubApi.clone({ storage: snp.storage, withoutNode: true, clonePathArray: true }) :
358                     null;
359
360             if (copiedApi) {
361                 copiedApi.pathArray.forEach(function (p) {
362                     p.hover = false;
363                 });
364
365                 PathUtilsService.fillPath(copiedApi.pathArray, snp.normalizedPath);
366             }
367
368             var searchedModule = PathUtilsService.getModuleNameFromPath(pathString);
369
370             if (mpSearchPath.indexOf(mountPrefix) !== -1 && copiedApi){
371                 copiedApi = $scope.selSubApi &&
372                 searchedModule === $scope.selSubApi.pathArray[1].module ?
373                     copiedApi :
374                     null;
375             }
376
377             return copiedApi;
378         }
379     }
380
381 });