Yangman - Refactor refresh/expand collections
[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', 'YangmanService',
12     ];
13
14     function RequestsListCtrl($filter, $mdDialog, $scope, HandleFileService, PathUtilsService, RequestsService,
15                               YangmanService) {
16         var vm = this;
17
18         vm.collectionList = RequestsService.createEmptyCollectionList('yangman_collectionsList');
19         vm.collectionsSortAsc = true;
20         vm.mainList = null;
21         vm.requestList = RequestsService.createEmptyHistoryList('yangman_requestsList');
22         vm.search = '';
23
24         vm.clearFilter = clearFilter;
25         vm.clearHistoryList = clearHistoryList;
26         vm.clearCollectionList = clearCollectionList;
27         vm.colMatchingReqsCount = colMatchingReqsCount;
28         vm.deselectAllRequests = deselectAllRequests;
29         vm.downloadCollection = downloadCollection;
30         vm.executeRequest = executeRequest;
31         vm.fakeFilter = fakeFilter;
32         vm.filterCol = filterCol;
33         vm.filterColName = filterColName;
34         vm.filterReq = filterReq;
35         vm.init = init;
36         vm.loadRequests = loadRequests;
37         vm.readCollectionFromFile = readCollectionFromFile;
38         vm.refreshCollections = refreshCollections;
39         vm.selectAllRequests = selectAllRequests;
40         vm.selectRequest = selectRequest;
41         vm.showData = showData;
42         vm.showDgDeleteCollection = showDgDeleteCollection;
43         vm.showDgDeleteRequests = showDgDeleteRequests;
44         vm.showDgEditCollection = showDgEditCollection;
45         vm.showDgSaveReq = showDgSaveReq;
46         vm.toggleCollectionsSort = toggleCollectionsSort;
47         vm.showForm = showForm;
48
49         $scope.$on('YANGMAN_REFRESH_COLLECTIONS', loadCollectionRequest);
50         $scope.$on('YANGMAN_REFRESH_HISTORY', loadHistoryRequests);
51
52         loadRequests();
53
54         /**
55          * Save request obje to collection from other controller
56          * @param reqObj
57          */
58         function saveRequestFromExt(event, args) {
59             vm.showDgSaveReq(args.params.event, args.params.reqObj, false);
60         }
61
62
63         /**
64          * Clear history requests list and save to storage
65          */
66         function clearHistoryList(ev) {
67             var confirm = $mdDialog.confirm()
68                 .title($filter('translate')('YANGMAN_DELETE_HISTORY_CONFIRM_TITLE'))
69                 .textContent($filter('translate')('YANGMAN_DELETE_HISTORY_CONFIRM_TEXT'))
70                 .ariaLabel($filter('translate')('YANGMAN_DELETE_HISTORY_CONFIRM_TITLE'))
71                 .targetEvent(ev)
72                 .ok($filter('translate')('YANGMAN_OK'))
73                 .cancel($filter('translate')('YANGMAN_CANCEL'));
74
75             $mdDialog.show(confirm).then(function (){
76                 vm.requestList.clear();
77                 vm.requestList.saveToStorage();
78                 $scope.rootBroadcast('YANGMAN_REFRESH_HISTORY');
79             });
80         }
81
82         /**
83          * Clear collections requests list and save to storage
84          */
85         function clearCollectionList(ev) {
86             var confirm = $mdDialog.confirm()
87                 .title($filter('translate')('YANGMAN_DELETE_COLLECTION_CONFIRM_TITLE'))
88                 .textContent($filter('translate')('YANGMAN_DELETE_COLLECTION_CONFIRM_TEXT'))
89                 .ariaLabel($filter('translate')('YANGMAN_DELETE_COLLECTION_CONFIRM_TITLE'))
90                 .targetEvent(ev)
91                 .ok($filter('translate')('YANGMAN_OK'))
92                 .cancel($filter('translate')('YANGMAN_CANCEL'));
93
94             $mdDialog.show(confirm).then(function (){
95                 vm.collectionList.clear();
96                 vm.collectionList.saveToStorage();
97                 $scope.rootBroadcast('YANGMAN_REFRESH_COLLECTIONS');
98             });
99         }
100
101         /**
102          * Create history request from other ctrl
103          * @param broadcastEvent
104          * @param params
105          */
106         function saveBcstedHistoryRequest(broadcastEvent, params) {
107             vm.requestList.addRequestToList(params.params);
108             vm.requestList.groupListByDate();
109             vm.requestList.saveToStorage();
110             loadHistoryRequests();
111         }
112
113         /**
114          * Clear value of input file used to import collection
115          */
116         function clearFileInputValue(){
117             angular.element(document).find('#importCollection').val('');
118         }
119
120         /**
121          * Importing collection from a file
122          * todo: error handling - msgs for user
123          * @param $fileContent
124          */
125         function readCollectionFromFile($fileContent) {
126             var data = $fileContent,
127                 checkArray = [
128                     'sentData',
129                     'receivedData',
130                     'path',
131                     'collection',
132                     'method',
133                     'status',
134                     'name',
135                 ];
136
137             if (data && YangmanService.validateFile(data, checkArray)){
138                 try {
139                     vm.collectionList.loadListFromFile(data);
140                     vm.collectionList.saveToStorage();
141                     clearFileInputValue();
142                 }
143                 catch (e) {
144                     clearFileInputValue();
145                     console.error('DataStorage error:', e);
146                 }
147             }
148             else {
149                 clearFileInputValue();
150             }
151         }
152
153         function toggleCollectionsSort() {
154             vm.collectionsSortAsc = !vm.collectionsSortAsc;
155         }
156
157         /**
158          * Export collection to json file
159          * @param {Collection} collection
160          */
161         function downloadCollection(collection) {
162
163             var cListJSON = vm.collectionList.getCollectionInJSON(collection.name);
164
165             HandleFileService.downloadFile(collection.name + '.json', cListJSON, 'json', 'charset=utf-8',
166                 function (){},
167                 function (e){
168                     console.error('ExportCollection error:', e);
169                 }
170             );
171         }
172
173         /**
174          * Fill request form in right panel with request data
175          * @param reqObj
176          */
177         function showForm(reqObj) {
178             var data = reqObj.method === 'GET' ? reqObj.receivedData : reqObj.sentData;
179
180             $scope.rootBroadcast('YANGMAN_FILL_NODE_FROM_REQ', { requestUrl: reqObj.path, requestData: data },
181                 function (){
182                     $scope.setRightPanelSection('form');
183                     $scope.rootBroadcast('YANGMAN_HEADER_INIT', { path: reqObj.path, method: reqObj.method });
184
185                     if ( $scope.node ) {
186                         // try to fill node
187                         YangmanService.fillNodeFromResponse($scope.node, data);
188                         $scope.node.expanded = true;
189                     }
190
191                 }
192             );
193
194         }
195
196         /**
197          * Force request header to execute request with data from reqObj
198          * @param reqObj
199          */
200         function executeRequest(reqObj) {
201             $scope.rootBroadcast(
202                 'YANGMAN_HEADER_INIT',
203                 { path: reqObj.path, method: reqObj.method },
204                 function (){
205                     $scope.rootBroadcast(
206                         'YANGMAN_EXECUTE_WITH_DATA',
207                         { data: reqObj.sentData },
208                         function (historyReq){
209                             showData(historyReq);
210                         }
211                     );
212                 }
213             );
214
215         }
216
217
218         /**
219          * Show current reqObj json data in right panel section
220          * @param reqObj
221          * @param dataType
222          */
223         function showData(reqObj) {
224
225             $scope.setRightPanelSection('req-data');
226             $scope.setJsonView(true, reqObj.method !== 'GET');
227
228             $scope.rootBroadcast('YANGMAN_HEADER_INIT', { path: reqObj.path, method: reqObj.method });
229
230             $scope.rootBroadcast(
231                 'YANGMAN_SET_CODEMIRROR_DATA_SENT',
232                 { data: reqObj.setDataForView(reqObj.sentData) }
233             );
234             $scope.rootBroadcast(
235                 'YANGMAN_SET_CODEMIRROR_DATA_RECEIVED',
236                 { data: reqObj.setDataForView(reqObj.receivedData) }
237             );
238
239             var data = reqObj.method === 'GET' ? reqObj.receivedData : reqObj.sentData;
240
241             $scope.rootBroadcast('YANGMAN_FILL_NODE_FROM_REQ', { requestUrl: reqObj.path, leftpanel: 0},
242                 function (){
243                     if ( $scope.node ) {
244                         // try to fill node
245                         YangmanService.fillNodeFromResponse($scope.node, data);
246                         $scope.node.expanded = true;
247                     }
248
249                 }
250             );
251         }
252
253         /**
254          * Clear current ctrl search value
255          */
256         function clearFilter(){
257             vm.search = '';
258         }
259
260         /**
261          * Dialog for deleting either selected requests or reqObj
262          *
263          * @param ev
264          * @param reqObj
265          */
266         function showDgDeleteRequests(ev, reqObj){
267             var confirm = $mdDialog.confirm()
268                 .title($filter('translate')('YANGMAN_DELETE_REQ_CONFIRM_TITLE'))
269                 .textContent($filter('translate')('YANGMAN_DELETE_REQ_CONFIRM_TEXT'))
270                 .ariaLabel($filter('translate')('YANGMAN_DELETE_REQ_CONFIRM_TITLE'))
271                 .targetEvent(ev)
272                 .ok($filter('translate')('YANGMAN_OK'))
273                 .cancel($filter('translate')('YANGMAN_CANCEL'));
274
275             $mdDialog.show(confirm).then(function (){
276                 if (reqObj){
277                     vm.mainList.deleteRequestItem(reqObj);
278                 }
279                 else {
280                     vm.mainList.selectedRequests.forEach(function (elem){
281                         vm.mainList.deleteRequestItem(elem);
282                     });
283                 }
284                 vm.mainList.saveToStorage();
285                 $scope.rootBroadcast('YANGMAN_REFRESH_HISTORY');
286             });
287         }
288
289
290         /**
291          * Dialog for deleting collection and refreshing collections
292          * @param ev
293          * @param collObj
294          */
295         function showDgDeleteCollection(ev, collObj){
296             var confirm = $mdDialog.confirm()
297                 .title($filter('translate')('YANGMAN_DELETE_COL_CONFIRM_TITLE') + ' ' + collObj.name + '?')
298                 .textContent($filter('translate')('YANGMAN_DELETE_COL_CONFIRM_TEXT'))
299                 .ariaLabel($filter('translate')('YANGMAN_DELETE_COL_CONFIRM_TITLE'))
300                 .targetEvent(ev)
301                 .ok($filter('translate')('YANGMAN_OK'))
302                 .cancel($filter('translate')('YANGMAN_CANCEL'));
303
304             $mdDialog.show(confirm).then(function (){
305                 ev.stopPropagation();
306                 vm.collectionList.deleteCollection(collObj);
307                 vm.collectionList.saveToStorage();
308                 refreshCollections();
309             });
310         }
311
312         /**
313          * Check if reqObj matches current search value
314          * @param reqObj
315          * @returns {boolean}
316          */
317         function filterReq(reqObj){
318             return reqObj.path.indexOf(vm.search) !== -1;
319         }
320
321         /**
322          * Check if collection name matches current search value or any collection req matches
323          * @param colObj
324          */
325         function filterCol(colObj){
326             return filterColName(colObj) || colObj.data.some(filterReq);
327         }
328
329         /**
330          * Get count of requests matching filter in collection colObj
331          * @param colObj
332          * @returns {*}
333          */
334         function colMatchingReqsCount(colObj){
335             return colObj.data.filter(vm.filterReq).length;
336         }
337
338         /**
339          * Check if collection name matches current filter
340          * @param colObj
341          * @returns {boolean}
342          */
343         function filterColName(colObj){
344             return colObj.name.indexOf(vm.search) !== -1;
345         }
346
347         /**
348          * Returns true
349          * @returns {boolean}
350          */
351         function fakeFilter(){
352             return true;
353         }
354
355         /**
356          * Show dialog for saving reqObj to collection (used for duplicate req too)
357          * @param ev
358          * @param reqObj
359          * @param duplicate
360          */
361         function showDgSaveReq(ev, reqObj, duplicate){
362
363             $mdDialog.show({
364                 controller: SaveReqDialogCtrl,
365                 controllerAs: 'dialog',
366                 templateUrl: $scope.globalViewPath + 'leftpanel/save-req-dialog.tpl.html',
367                 parent: angular.element('#yangmanModule'),
368                 targetEvent: ev,
369                 clickOutsideToClose: true,
370                 locals: {
371                     requests: reqObj ? [reqObj] : vm.requestList.selectedRequests,
372                     collectionNames: vm.collectionList.getCollectionNames(),
373                     duplicate: duplicate || false,
374                 },
375             }).then(saveRequests);
376         }
377
378         /**
379          * Add each request from requests array to collectionList and save
380          * @param requests
381          */
382         function saveRequests(requests){
383             requests.forEach(function (reqObj){
384                 vm.collectionList.addRequestToList(reqObj);
385                 vm.collectionList.saveToStorage();
386                 $scope.rootBroadcast('YANGMAN_REFRESH_COLLECTIONS');
387             });
388         }
389
390
391         /**
392          * Dialog for editing collection name (used for duplicating collection too)
393          * @param ev
394          * @param collection
395          * @param {boolean} duplicate
396          */
397         function showDgEditCollection(ev, collection, duplicate){
398             $mdDialog.show({
399                 controller: EditCollectionDialogCtrl,
400                 controllerAs: 'dialog',
401                 templateUrl: $scope.globalViewPath + 'leftpanel/edit-collection-dialog.tpl.html',
402                 parent: angular.element('#yangmanModule'),
403                 targetEvent: ev,
404                 clickOutsideToClose: true,
405                 locals: {
406                     collection: collection,
407                     allCollections: vm.collectionList.collections,
408                     duplicate: duplicate,
409                 },
410             }).then(duplicate ? duplicateCollection : changeCollectionName);
411         }
412
413         /**
414          * Rename collection
415          * @param {array} names 0. element is old name, 1. element is new name
416          */
417         function changeCollectionName(names){
418             vm.collectionList.renameCollection(names[0], names[1]);
419             vm.collectionList.saveToStorage();
420             refreshCollections();
421         }
422
423         /**
424          * Create collection duplicate, save and refresh collections
425          * @param {array} names 0. element is old name, 1. element is new name
426          */
427         function duplicateCollection(names){
428             vm.collectionList.duplicateCollection(names[0], names[1]);
429             vm.collectionList.saveToStorage();
430             refreshCollections();
431         }
432
433         /**
434          *
435          * @param list collectionList or requestList object
436          */
437         function init(list){
438             vm.mainList = list;
439
440             if (list === vm.requestList){
441                 // saving from request header after execution
442                 $scope.$on('YANGMAN_SAVE_EXECUTED_REQUEST', saveBcstedHistoryRequest);
443                 // saving from request header
444                 $scope.$on('YANGMAN_SAVE_REQUEST_TO_COLLECTION', saveRequestFromExt);
445             } else {
446                 // saving collections expanded status on refresh
447                 $scope.$on('YANGMAN_REFRESH_AND_EXPAND_COLLECTIONS', function(event, params){
448                     $scope.rootBroadcast('YANGMAN_REFRESH_COLLECTIONS');
449                     (params.cbk || angular.noop)();
450                 });
451             }
452
453         }
454
455         /**
456          * Loading history request and grouping by date
457          */
458         function loadHistoryRequests(){
459             vm.requestList.loadListFromStorage();
460             vm.requestList.groupListByDate();
461         }
462
463         /**
464          * Loading collections
465          */
466         function loadCollectionRequest(){
467             vm.collectionList.loadListFromStorage();
468         }
469
470         /**
471          * Loading both history and collections reqs
472          */
473         function loadRequests(){
474             loadHistoryRequests();
475             loadCollectionRequest();
476         }
477
478         /**
479          * Request in list selection
480          * For history reqs it is possible multiselect, thats why event.ctrlKey is used
481          * @param event
482          * @param requestObj
483          */
484         function selectRequest(event, requestObj){
485             vm.mainList.toggleReqSelection(!event.ctrlKey, requestObj);
486             $scope.setHistoryReqsSelected(vm.requestList.selectedRequests.length > 0);
487         }
488
489         /**
490          * Deselect history requests
491          */
492         function deselectAllRequests(){
493             vm.mainList.deselectReqs();
494         }
495
496         /**
497          * Select history requests
498          */
499         function selectAllRequests(){
500             deselectAllRequests();
501             vm.mainList.dateGroups.forEach(function(group){
502                 vm.mainList.selectReqs(group.requests);
503             });
504         }
505
506         /**
507          * Refresh and expand collections
508          */
509         function refreshCollections(){
510             var collectionNames = vm.collectionList.getExpandedCollectionNames();
511             $scope.rootBroadcast('YANGMAN_REFRESH_AND_EXPAND_COLLECTIONS', null, function(){
512                 vm.collectionList.expandCollectionByNames(collectionNames);
513             });
514         }
515
516     }
517
518 });