Updated Sparky to add ECOMP functionality Browse, Specialized Search, BYOQ, and the...
[aai/sparky-fe.git] / src / app / byoq / CustomDSLSaveLoad.jsx
1 /*
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2021 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *       http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 import React, { Component } from 'react';
22
23 import commonApi from 'utils/CommonAPIService.js';
24 import {GlobalExtConstants} from 'utils/GlobalExtConstants.js';
25 import Spinner from 'utils/SpinnerContainer.jsx';
26 import Grid from 'react-bootstrap/lib/Grid';
27 import Row from 'react-bootstrap/lib/Row';
28 import Col from 'react-bootstrap/lib/Col';
29 import Button from 'react-bootstrap/lib/Button';
30 import Modal from 'react-bootstrap/lib/Modal';
31 import Tabs from 'react-bootstrap/lib/Tabs';
32 import Tab from 'react-bootstrap/lib/Tab';
33 import Pagination from 'react-js-pagination';
34 import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';
35 import Tooltip from 'react-bootstrap/lib/Tooltip';
36 import Panel from 'react-bootstrap/lib/Panel';
37 import {GeneralCommonFunctions} from 'utils/GeneralCommonFunctions.js';
38 import Alert from 'react-bootstrap/lib/Alert';
39 import MultiSelectDropDown from 'generic-components/MultiSelectDropDown.jsx';
40 let ENVIRONMENT = GlobalExtConstants.ENVIRONMENT;
41 let APERTURE_SERVICE = JSON.parse(sessionStorage.getItem(ENVIRONMENT + 'APERTURE_SERVICE'));
42
43 let INVLIST = GlobalExtConstants.INVLIST;
44
45 const settings = {
46         'NODESERVER': INVLIST.NODESERVER,
47         'PROXY': INVLIST.PROXY,
48         'PREFIX': INVLIST.PREFIX,
49         'VERSION': INVLIST.VERSION,
50     'USESTUBS': INVLIST.useStubs,
51     'TABULAR': INVLIST.TABULAR,
52     'APERTURE': INVLIST.APERTURE,
53     'TABULARVERSION': INVLIST.TABULARVERSION
54 };
55
56 /**
57  * This class is used to handle any saving or loading of dsl queries
58  */
59
60 class CustomDSLSaveLoad extends Component {
61
62   constructor(props) {
63     console.log(props);
64     super(props);
65     APERTURE_SERVICE=JSON.parse(sessionStorage.getItem(ENVIRONMENT + 'APERTURE_SERVICE'));
66     this.state = {
67         enablePublicQueriesBusyFeedback: false,
68         enableCommunityQueriesBusyFeedback: false,
69         enablePersonalQueriesBusyFeedback: false,
70         enableDeleteBusyFeedback: false,
71         loadedPublicQueries: [],
72         loadedCommunityQueries: [],
73         loadedPersonalQueries: [],
74         filteredPublicEntries: [],
75         filteredCommunityEntries: [],
76         filteredPersonalEntries: [],
77         initialFilteredPublicEntries: [],
78         initialFilteredCommunityEntries: [],
79         initialFilteredPersonalEntries:[],
80         totalPublicResults: 0,
81         totalCommunityResults: 0,
82         totalPersonalResults: 0,
83         queriesPublicErrMsg: false,
84         queriesCommunityErrMsg: false,
85         queriesPersonalErrMsg: false,
86         deleteErrMsg: false,
87         deleteSuccessfulMsg: false,
88         focusedEntryName: '',
89         focusedEntryType: false,
90         showDeleteModal: false,
91         filterPublicCriteria: '',
92         filterCommunityCriteria: '',
93         filterPersonalCriteria: '',
94         displayValue:'Category',
95         selectedOption:{"public":[],"community":[],"personal":[]},
96         filterText:'',
97         activeType:'public',
98         queryId:'',
99         loadQueryList:[],
100         publicLoadQueryList:[],
101         personalLoadQueryList:[],
102         communityLoadQueryList:[],
103         loadQueryLimit:parseInt(sessionStorage.getItem(ENVIRONMENT + 'LOADTEMPLATE_MAX_COUNT')),
104         loadQueryFlag:true,
105         selectedCount:0
106     };
107     settings['ISAPERTURE']=APERTURE_SERVICE;
108   }
109   componentDidMount = () => {
110     this.setState({enablePersonalQueriesBusyFeedback:true,enablePublicQueriesBusyFeedback:true,enableCommunityQueriesBusyFeedback:true});
111     this.getQueries();
112   };
113   componentWillUnmount  = () => {};
114
115   filterPublicList = (event) =>{
116       this.filterPublicListWithCategory(event.target.value);
117   }
118   filterPublicListWithCategory = (value) =>{
119      var updatedList = this.state.loadedPublicQueries;
120      updatedList = Object.keys(updatedList).filter(key => {
121         return JSON.stringify(updatedList[key]).toLowerCase().search(value.toLowerCase()) !== -1;
122      }).reduce( (res, key) => Object.assign(res, { [key]: updatedList[key] }), {} );     
123      let filterList=this.filterUpdatedList(updatedList, "public");
124      console.log('filterPublicListWithCategory filterList>>>>>',filterList);
125      this.setState({filteredPublicEntries: filterList, totalPublicResults: Object.keys(filterList).length, filterPublicCriteria: value,filterText: value.toLowerCase()});
126    }
127   filterCommunityList = (event) =>{
128       this.filterCommunityListWithCategory(event.target.value);
129   }
130   filterCommunityListWithCategory = (value) =>{
131      var updatedList = this.state.loadedCommunityQueries;
132      updatedList = Object.keys(updatedList).filter(key => {
133         return JSON.stringify(updatedList[key]).toLowerCase().search(value.toLowerCase()) !== -1;
134      }).reduce( (res, key) => Object.assign(res, { [key]: updatedList[key] }), {} );
135      let filterList=this.filterUpdatedList(updatedList, "community");
136      console.log('filterCommunityListWithCategory filterList>>>>>',filterList);
137      this.setState({filteredCommunityEntries: filterList, totalCommunityResults: Object.keys(filterList).length, filterCommunityCriteria: value,filterText: value.toLowerCase()});
138   }
139   filterPersonalList = (event) =>{
140       this.filterPersonalListWithCategory(event.target.value);
141   }
142   filterPersonalListWithCategory =(value) =>{
143      var updatedList = this.state.loadedPersonalQueries;
144      updatedList = Object.keys(updatedList).filter(key => {
145         return JSON.stringify(updatedList[key]).toLowerCase().search(value.toLowerCase()) !== -1;
146      }).reduce( (res, key) => Object.assign(res, { [key]: updatedList[key] }), {} );
147      let filterList=this.filterUpdatedList(updatedList, "personal");
148      console.log('filterPersonalListWithCategory filterList>>>>>',filterList);     
149      this.setState({filteredPersonalEntries: filterList, totalPersonalResults: Object.keys(filterList).length, filterPersonalCriteria: value,filterText: value.toLowerCase()});
150   }
151   filterUpdatedList = (updatedList, type) =>{
152     let selectedCategory = this.state.selectedOption[type];
153     let filterList = [];
154     let selectedOption = [];
155     if(selectedCategory.length > 0){
156        selectedOption = Object.keys(selectedCategory).map((index)=>{
157            return selectedCategory[index].value;
158        }); 
159        Object.keys(updatedList).map((key) => {
160            Object.keys(updatedList[key]).map((entry) => {
161                if(entry === 'category' && selectedOption.indexOf(updatedList[key][entry]) !==-1){
162                    filterList[key]=updatedList[key];                  
163                }
164            })
165        });
166     }else{
167        filterList=updatedList;
168     }
169     return filterList;
170   }
171   processQueryResponse = (res) => {
172     var formattedList = [];
173     for(var i = 0; i < res.length; i++){
174         var newQueryObj = {};
175         var requiredFieldCount = 0;
176         if(res[i]){
177             newQueryObj.isSelect=false;
178             newQueryObj.id = res[i].id;
179             newQueryObj['is_aggregate'] = false;
180             newQueryObj['is_public'] = false;
181             newQueryObj['community_shared'] = false;
182             newQueryObj['template_details'] = [];
183             for(var j = 0; j < res[i].cols.length; j++){
184                 if(res[i].cols[j].name){
185                     if(res[i].cols[j].name === 'query_name'){
186                         requiredFieldCount++;
187                         newQueryObj.name = res[i].cols[j].value;
188                     }
189                     if(res[i].cols[j].name === 'creator'){
190                         requiredFieldCount++;
191                         newQueryObj.creator = res[i].cols[j].value;
192                     }
193                     if(res[i].cols[j].name === 'dsl'){
194                         requiredFieldCount++;
195                         newQueryObj.dsl = res[i].cols[j].value;
196                     }
197                     if(res[i].cols[j].name === 'description'){
198                         newQueryObj.description = res[i].cols[j].value;
199                     }
200                     if(res[i].cols[j].name === 'is_aggregate'){
201                         newQueryObj['is_aggregate'] = res[i].cols[j].value;
202                     }
203                     if(res[i].cols[j].name === 'is_public'){
204                         newQueryObj['is_public'] = res[i].cols[j].value;
205                     }
206                     if(res[i].cols[j].name === 'community_shared'){
207                         newQueryObj['community_shared'] = res[i].cols[j].value;
208                     }
209                     if(res[i].cols[j].name === 'template_details'){
210                         newQueryObj['template_details'] = res[i].cols[j].value;
211                     }
212                     if(res[i].cols[j].name === 'category'){
213                         newQueryObj['category'] = res[i].cols[j].value;
214                     }
215                 }
216             }
217             newQueryObj.version = res[i].version;
218         }
219         if(requiredFieldCount === 3){
220             formattedList[res[i].id] = newQueryObj;
221         }else{
222             console.log('Issue occurred on query list processing for the following element: ' + JSON.stringify(newQueryObj));
223         }
224     }
225     return formattedList;
226   }
227   
228   getPublicQueries = () => {
229     settings['ISTABULAR'] = true;
230     return new Promise((resolve, reject) => {
231                         commonApi(settings, 'queries/is_public=true', 'GET', null, 'BYOQPublicQueries', GlobalExtConstants.OVERRIDE_DOMAIN)
232                                         .then(res => {
233                                                 console.log('res:' + res.data, 'load');
234                                                 if(res.status === 200 || res.status === 404){
235                                                     if(res.data.status && (res.data.status !== 200 && res.data.status !== 201 && res.data.status !== 404)){
236                                                         this.triggerError(res.data);
237                                                     }else{
238                                                         var list = this.processQueryResponse(res.data);
239                                                         this.setState({
240                                              enablePublicQueriesBusyFeedback:false,
241                                              filteredPublicEntries: list,
242                                              initialFilteredPublicEntries: list,
243                                              totalPublicResults: Object.keys(list).length,
244                                              loadedPublicQueries: list
245                                              });
246                                           this.runPublicFilter();
247                                           resolve(list);
248                                       }
249                                   }else{
250                                     this.triggerError(res.data, 'public_load');
251                                   }
252                                 resolve([]);
253                                         }, error=>{
254                                             if(error.response.status === 404){
255                                                 this.setState({
256                                                       enablePublicQueriesBusyFeedback:false,
257                                                       filteredPublicEntries: [],
258                                                       totalPublicResults: 0,
259                                                       initialFilteredPublicEntries:[],
260                                                       loadedPublicQueries: []
261                                                     });
262                                             }else{
263                                                 this.triggerError(error.response.data, 'public_load');
264                                             }
265                                             resolve([]);
266                                         }).catch(error => {
267                                             this.triggerError(error, 'public_load');
268                                             resolve([]);
269                             })
270                         })
271     }
272   getCommunityQueries = () => {
273       settings['ISTABULAR'] = true;
274       return new Promise((resolve, reject) => {
275                           commonApi(settings, 'queries/community_shared=true', 'GET', null, 'BYOQCommunityQueries', GlobalExtConstants.OVERRIDE_DOMAIN)
276                                         .then(res => {
277                                                 console.log('res:' + res.data, 'load');
278                                                 if(res.status === 200 || res.status === 404){
279                                                     if(res.data.status && (res.data.status !== 200 && res.data.status !== 201 && res.data.status !== 404)){
280                                                         this.triggerError(res.data);
281                                                     }else{
282                                                         var list = this.processQueryResponse(res.data);
283                                                         this.setState({
284                                                enableCommunityQueriesBusyFeedback:false,
285                                                filteredCommunityEntries: list,
286                                                initialFilteredCommunityEntries: list,
287                                                totalCommunityResults: Object.keys(list).length,
288                                                loadedCommunityQueries: list
289                                                });
290                                             this.runCommunityFilter();
291                                             resolve(list);
292                                         }
293                                     }else{
294                                       this.triggerError(res.data, 'community_load');
295                                     }
296                                   resolve([]);
297                                         }, error=>{
298                                             if(error.response.status === 404){
299                                                 this.setState({
300                                                         enableCommunityQueriesBusyFeedback:false,
301                                                         filteredCommunityEntries: [],
302                                                         totalCommunityResults: 0,
303                                                         initialFilteredCommunityEntries:[],
304                                                         loadedCommunityQueries: []
305                                                       });
306                                             }else{
307                                                 this.triggerError(error.response.data, 'community_load');
308                                             }
309                                             resolve([]);
310                                         }).catch(error => {
311                                             this.triggerError(error, 'community_load');
312                                             resolve([]);
313                               })
314                           })
315   }
316   getPrivateQueries = () => {
317         settings['ISTABULAR'] = true;
318         let query='queries/is_public=false';
319         if(sessionStorage.getItem(GlobalExtConstants.ENVIRONMENT + 'userId')){
320             query+='&creator=' + sessionStorage.getItem(GlobalExtConstants.ENVIRONMENT + 'userId');
321         }        
322         return new Promise((resolve, reject) => {
323           commonApi(settings, 'queries/is_public=false&creator=' + sessionStorage.getItem(GlobalExtConstants.ENVIRONMENT + 'userId'), 'GET', null, 'BYOQPersonalQueries', GlobalExtConstants.OVERRIDE_DOMAIN)
324                         .then(res => {
325                                 console.log('res:' + res.data, 'load');
326                                 if(res.status === 200 || res.status === 404){
327                                     if(res.data.status && (res.data.status !== 200 && res.data.status !== 201 && res.data.status !== 404)){
328                                         this.triggerError(res.data);
329                                     }else{
330                                         var list = this.processQueryResponse(res.data);
331                                         this.setState({
332                                  enablePersonalQueriesBusyFeedback:false,
333                                  filteredPersonalEntries: list,
334                                  initialFilteredPersonalEntries: list,
335                                  totalPersonalResults: Object.keys(list).length,
336                                  loadedPersonalQueries: list
337                                  });
338                               this.runPersonalFilter();
339                               resolve(list);
340                           }
341                       }else{
342                         this.triggerError(res.data, 'personal_load');
343                       }
344                       resolve([]);
345                         }, error=>{
346                             if(error.response.status === 404){
347                                 this.setState({
348                                           enablePersonalQueriesBusyFeedback:false,
349                                           filteredPersonalEntries: [],
350                                           initialFilteredPersonalEntries: [],
351                                           totalPersonalResults: 0,
352                                           loadedPersonalQueries: []
353                                         });
354                             }else{
355                                 this.triggerError(error.response.data, 'personal_load');
356                             }
357                              resolve([]);
358                         }).catch(error => {
359                             this.triggerError(error, 'personal_load');
360                             resolve([]);
361                 })
362            })
363   }
364   getQueries = () =>{
365     var state = this;
366     this.getCommunityQueries();
367     Promise.all([
368       this.getPublicQueries(),
369       this.getPrivateQueries()
370       ])
371       .then(function (responses) {
372         var result = Object.assign({}, responses[0], responses[1]);
373         state.props.setQueriesState(result);
374         state.setState({loadQueryList:[],publicLoadQueryList:[],personalLoadQueryList:[],communityLoadQueryList:[],selectedCount:0});
375       }).catch(function (error) {
376         console.log(error);
377       });
378   };
379   triggerError = (error, type) => {
380     console.error('[CustomDslSaveLoad.jsx] error : ', JSON.stringify(error));
381         let errMsg = '';
382         if(error.status && error.message){
383             errMsg += "Error Occurred: " + error.status + ' - ' +error.message;
384         }else{
385             errMsg += "Error Occurred: " + JSON.stringify(error);
386         }
387         console.log(errMsg);
388         if(type === 'public_load'){
389         this.setState({queriesPublicErrMsg:errMsg,
390                        enablePublicQueriesBusyFeedback:false,
391                        filteredPublicEntries: [],
392                        totalPublicResults: 0,
393                        loadedPublicQueries: []});
394         var result = Object.assign({}, [], this.state.loadedPersonalQueries);
395         this.props.setQueriesState(result);
396     }else if(type === 'personal_load'){
397         this.setState({queriesPersonalErrMsg:errMsg,
398                        enablePersonalQueriesBusyFeedback:false,
399                        filteredPersonalEntries: [],
400                        totalPersonalResults: 0,
401                        loadedPersonalQueries: []});
402         var result = Object.assign({}, this.state.loadedPublicQueries, []);
403         this.props.setQueriesState(result);
404     }else if(type === 'community_load'){
405         this.setState({queriesCommunityErrMsg:errMsg,
406                        enableCommunityQueriesBusyFeedback:false,
407                        filteredCommunityEntries: [],
408                        totalCommunityResults: 0,
409                        loadedCommunityQueries: []});
410         var result = Object.assign({}, this.state.loadedCommunityQueries, []);
411         this.props.setQueriesState(result);
412     }else if (type === 'delete'){
413         this.setState({deleteErrMsg: errMsg + " - Failed to delete query : " + this.state.focusedEntryName, enableDeleteBusyFeedback:false});
414         GeneralCommonFunctions.scrollTo("deleteError");
415     }else{
416         console.log('[CustomDslSaveLoad.jsx] :: triggerError invoked with invalid type : ' + type);
417     }
418   }
419
420   runPublicFilter = () =>{
421     var updatedList = this.state.loadedPublicQueries;
422     updatedList = Object.keys(updatedList).filter(key => {
423                 return JSON.stringify(updatedList[key]).toLowerCase().search(this.state.filterPublicCriteria.toLowerCase()) !== -1;
424              }).reduce( (res, key) => Object.assign(res, { [key]: updatedList[key] }), {} );
425              this.setState({filteredPublicEntries: updatedList, totalPublicResults: Object.keys(updatedList).length},()=>{if(this.state.selectedOption["public"].length>0){this.filterPublicListWithCategory(this.state.filterPublicCriteria)}});
426   }
427   runCommunityFilter = () =>{
428     var updatedList = this.state.loadedCommunityQueries;
429     updatedList = Object.keys(updatedList).filter(key => {
430                 return JSON.stringify(updatedList[key]).toLowerCase().search(this.state.filterCommunityCriteria.toLowerCase()) !== -1;
431              }).reduce( (res, key) => Object.assign(res, { [key]: updatedList[key] }), {} );
432              this.setState({filteredCommunityEntries: updatedList, totalCommunityResults: Object.keys(updatedList).length},()=>{if(this.state.selectedOption["community"].length>0){this.filterCommunityListWithCategory(this.state.filterCommunityCriteria)}});
433   }
434   runPersonalFilter = () =>{
435     var updatedList = this.state.loadedPersonalQueries;
436     updatedList = Object.keys(updatedList).filter(key => {
437                 return JSON.stringify(updatedList[key]).toLowerCase().search(this.state.filterPersonalCriteria.toLowerCase()) !== -1;
438              }).reduce( (res, key) => Object.assign(res, { [key]: updatedList[key] }), {} );
439              this.setState({filteredPersonalEntries: updatedList, totalPersonalResults: Object.keys(updatedList).length},()=>{if(this.state.selectedOption["personal"].length>0){this.filterPersonalListWithCategory(this.state.filterPersonalCriteria)}});
440   }
441
442   addElement = (element) =>{
443     var updatedList = this.state.loadedPublicQueries;
444     updatedList[element.id] = element[0];
445     this.setState({loadedPublicQueries: updatedList});
446     this.props.setQueriesState(updatedList);
447     this.runPublicFilter();
448   }
449
450   submitDelete = () =>{
451      var loadedQueries = [];
452      if(this.state.focusedEntryType === "personal"){
453         loadedQueries = this.state.loadedPersonalQueries;
454      }else{
455         loadedQueries = this.state.loadedPublicQueries;
456      }
457      this.setState({enableDeleteBusyFeedback:true});
458      settings['ISTABULAR'] = true;
459      commonApi(settings, 'queries/' + encodeURIComponent(this.state.queryId), 'DELETE', '{\"id\":\"'
460         + encodeURIComponent(this.state.queryId) + '\"}', 'BYOQDeleteQuery', GlobalExtConstants.OVERRIDE_DOMAIN, null,
461         [{
462             "name":"If-Match",
463             "value": loadedQueries[this.state.queryId].version
464          }])
465                         .then(res => {
466                                 console.log('res:' + res.data);
467                                 if(res.status === 200){
468                                     if(res.data.status && (res.data.status !== 200 && res.data.status !== 201)){
469                                         this.triggerError(res.data, 'delete');
470                                     }else{
471                                         var updatedList = loadedQueries;
472                                 //remove the entry from the list
473                                 updatedList = Object.keys(updatedList).filter(key => {
474                                    return key !== this.state.queryId;
475                                 }).reduce( (res, key) => Object.assign(res, { [key]: updatedList[key] }), {} );
476                                 this.setState({showDeleteModal:false,
477                                                focusedEntryName: '',
478                                                enableDeleteBusyFeedback:false,
479                                                deleteSuccessfulMsg: "Successfully deleted query : " + this.state.focusedEntryName});
480                                 GeneralCommonFunctions.scrollTo("deleteSuccess");
481                                 if(this.state.focusedEntryType === "personal"){
482                                    this.getCommunityQueries();
483                                    this.setState({loadedPersonalQueries: updatedList});
484                                    var result = Object.assign({}, this.state.loadedPublicQueries, updatedList);
485                                    this.props.setQueriesState(result);
486                                 }else{
487                                    this.setState({loadedPublicQueries: updatedList});
488                                    var result = Object.assign({}, updatedList, this.state.loadedPersonalQueries);
489                                    this.props.setQueriesState(result);
490                                 }
491                                 this.runPublicFilter();
492                                 this.runCommunityFilter();
493                                 this.runPersonalFilter();
494                             }
495                                 }else{
496                                     this.triggerError(res.data, 'delete');
497                                 }
498                         }, error=>{
499                             this.triggerError(error.response.data, 'delete');
500                         }).catch(error => {
501                             this.triggerError(error, 'delete');
502      });
503   };
504
505   openDeleteModal = (id,name, isPublic) =>{
506     var focusedEntryType = "public";
507     if(isPublic === "true"){
508         focusedEntryType = "public";
509     }else{
510         focusedEntryType = "personal";
511     }
512     this.setState({showDeleteModal:true, focusedEntryName: name, focusedEntryType: focusedEntryType, deleteSuccessfulMsg:false, deleteErrMsg:false, queryId:id});
513   };
514
515   closeDeleteModal = () =>{
516     this.setState({showDeleteModal:false, focusedEntryName: '', focusedEntryType: false, deleteSuccessfulMsg:false, deleteErrMsg:false, queryId:''});
517   };
518
519   loadQuery = (e) =>{
520     this.loadQueryData(e.target.value,0);
521   };
522   loadQueryData=(queryTemp, id)=>{
523     let splitString = queryTemp.split('||');
524     let name = splitString[0];
525     let description = splitString[1];
526     let category=(splitString[2] !== 'undefined')? splitString[2]:'';
527     let dsl = splitString[3];
528     let isAggregate = splitString[4];
529     let type = splitString[5];
530     let queryId = splitString[6];
531     let isCommunityShared = splitString[7];
532     let templateDetails = splitString[8];
533     this.props.loadCallback(name, description, category, dsl, isAggregate, type, queryId, isCommunityShared, id, templateDetails, false);
534   };
535   loadBulkCallback =() =>{
536     this.props.loadBulkCallback(this.state.loadQueryList);
537   }
538   loadAndRunQuery = (e) =>{
539     let splitString = (e.target.value).split('||');
540     let dsl = splitString[0];
541     let isAggregate = splitString[1];
542     this.props.loadCallback('', '', '', dsl, isAggregate, null, '', null, 0, [], true);
543   };
544   onMultiSelectPublicDropdownSelect = (selectedOption) =>{
545     console.log('onMultiSelectPublicDropdownSelect selectedList',selectedOption);
546     var tempSelection = this.state.selectedOption;
547     tempSelection["public"] = selectedOption;
548     this.setState({selectedOption:tempSelection},()=>{this.filterPublicListWithCategory(this.state.filterPublicCriteria)});
549   };
550   onMultiSelectCommunityDropdownSelect = (selectedOption) =>{
551     console.log('onMultiSelectCommunityDropdownSelect selectedList',selectedOption);
552     var tempSelection = this.state.selectedOption;
553     tempSelection["community"] = selectedOption;
554     this.setState({selectedOption:tempSelection},()=>{this.filterCommunityListWithCategory(this.state.filterCommunityCriteria)});
555   };
556   onMultiSelectPersonalDropdownSelect = (selectedOption) =>{
557     console.log('onMultiSelectPersonalDropdownSelect selectedList',selectedOption);
558     var tempSelection = this.state.selectedOption;
559     tempSelection["personal"] = selectedOption;
560     this.setState({selectedOption:tempSelection},()=>{this.filterPersonalListWithCategory(this.state.filterPersonalCriteria)});
561   };
562   prepareMultiOptions = (type) => {
563     //this.setState({activeType:type});
564     let filteredEntries=[];
565     if(type==='public'){
566         filteredEntries=this.state.initialFilteredPublicEntries;
567     }else if(type==='community'){
568         filteredEntries=this.state.initialFilteredCommunityEntries;
569     }else{
570         filteredEntries=this.state.initialFilteredPersonalEntries;
571     }
572     let dupArray=[];
573     let  multiOption=Object.keys(filteredEntries).map((entry, idx) => {
574                 let obj ={};
575                 if(filteredEntries[entry]['category'] && dupArray.indexOf(filteredEntries[entry]['category']) === -1){
576                     obj['value']=filteredEntries[entry]['category'];
577                     obj['label']= filteredEntries[entry]['category'];
578                     dupArray.push(filteredEntries[entry]['category']);
579                 }else{
580                     obj='';
581                 }
582                 return obj;       
583             });    
584      let filterMultiOption = multiOption.filter((entry) => {
585             if(entry !== '') return entry;             
586      });    
587      console.log('filterMultiOption>>>>>',filterMultiOption);   
588      return filterMultiOption;       
589   };
590   editSavedQuery = (e) =>{
591     let splitString = (e.target.value).split('||');
592     let name = splitString[0];
593     let description = splitString[1];
594     let category = (splitString[2] !== 'undefined')? splitString[2]:'';
595     let dsl = atob(splitString[3]).replace('<pre>','').replace('</pre>','');
596     let isAggregate = splitString[4];
597     let type = splitString[5];
598     let queryId= splitString[6];
599     let isCommunityShared = splitString[7];
600     let templateDetails = splitString[8];
601     this.props.editCallback(name, description, category, dsl, isAggregate, type, queryId, isCommunityShared, templateDetails);
602   };
603   loadAllQueries = () =>{
604     console.log('this.state.loadQueryList>>>>',this.state.loadQueryList);
605     let loadQueryList=this.state.loadQueryList;
606     for(var l=0;l<loadQueryList.length;l++){
607         this.loadQueryData(loadQueryList[l],l);
608     }
609   };
610   onSelectCheckbox=(e) =>{
611     let splitString = (e.target.value).split('||');   
612     let type = splitString[5];
613     let queryId=splitString[6];
614     let queryList='';
615     let loadQuery='';
616     if(type =='public'){
617         queryList=this.state.filteredPublicEntries;
618         loadQuery= this.state.publicLoadQueryList;
619     }else if (type == 'personal'){
620         queryList=this.state.filteredPersonalEntries;
621         loadQuery= this.state.personalLoadQueryList;        
622     }else{
623         queryList=this.state.filteredCommunityEntries;
624         loadQuery= this.state.communityLoadQueryList;
625     }
626     let flag= true;
627     if (e.target.checked) {        
628         if(loadQuery.length<10){
629             loadQuery.push(e.target.value);
630             queryList[queryId].isSelect=true;        
631         }    
632     }else{
633         let index=loadQuery.indexOf(e.target.value);
634         loadQuery.splice(index,1);
635         queryList[queryId].isSelect=false;         
636     }
637     flag=(loadQuery.length<=10)?true:false;
638     if(type=='public'){
639         this.setState({loadQueryList:loadQuery,publicLoadQueryList:loadQuery,personalLoadQueryList:[],communityLoadQueryList:[],filteredPublicEntries:queryList,loadQueryFlag:flag,selectedCount:loadQuery.length});
640     }else if(type=='personal'){
641         this.setState({loadQueryList:loadQuery,personalLoadQueryList:loadQuery,publicLoadQueryList:[],communityLoadQueryList:[],filteredPersonalEntries:queryList,loadQueryFlag:flag,selectedCount:loadQuery.length});
642     } else{
643         this.setState({loadQueryList:loadQuery,communityLoadQueryList:loadQuery,publicLoadQueryList:[],personalLoadQueryList:[],filteredCommunityEntries:queryList,loadQueryFlag:flag,selectedCount:loadQuery.length});
644     }   
645   }
646   render() {
647         let savedQueryCard = (type, totalCount, filterList, filteredEntries) =>{
648                                 let onMultiSelectDropdownSelect= (type==='public') ? this.onMultiSelectPublicDropdownSelect : (type==='community') ? this.onMultiSelectCommunityDropdownSelect : this.onMultiSelectPersonalDropdownSelect;
649                                 return <div className='card d3-model-card'>
650                                           <div className={'card-header ' + (this.props.isSavedQueryFlow ? 'show' : 'hidden')}>
651                                                <div>
652                                                  <h3>Find A Query</h3>
653                                                </div>
654                                           </div>
655                                           <div className='card-header'>
656                                                <div>
657                                                  <div style={{width:'82%',float:'left'}}>
658                                                     <h5>Total Saved Queries: <strong>{totalCount}</strong></h5>
659                                                  </div>
660                                                  <div className={(this.props.isSavedQueryFlow ? 'show' : 'hidden')}>
661                                                     <OverlayTrigger  placement='top' overlay={<Tooltip id='tooltip-top'>{'Enabled for up to '+this.state.loadQueryLimit+' Queries'}</Tooltip>}>
662                                                                                                     <span className="d-inline-block" style={{display: 'inline-block'}}>
663                                                             <button className='btn btn-outline-primary' type='button' onClick={()=>this.loadBulkCallback()} disabled={!(this.state.loadQueryList.length<=10 && this.state.loadQueryList.length>0)}>Load Selected Queries</button>
664                                                         </span>
665                                                     </OverlayTrigger>
666                                                  </div>                                                             
667                                                </div>
668                                                <div>
669                                                    <form>
670                                                        <div className='alignFormTwinElements'>
671                                                        <fieldset className="form-group">
672                                                            <input type="text" className="form-control form-control-lg" placeholder="Search" onChange={filterList}/>
673                                                        </fieldset>
674                                                        </div>
675                                                        <div className='alignFormTwinElements'>
676                                                        <fieldset className="form-group">
677                                                             <MultiSelectDropDown
678                                                                     options={this.prepareMultiOptions(type)}
679                                                                     displayValue={this.state.displayValue}
680                                                                     triggerSelect={onMultiSelectDropdownSelect}
681                                                             />
682                                                         </fieldset>
683                                                        </div>
684                                                    </form>
685                                                </div>
686                                           </div>
687                                           <div className='card-content model-card-content'>
688                                                  <table className="table table-hover table-striped">
689                                                    <thead>
690                                                      <tr>
691                                                        <th scope='col' className={(this.props.isSavedQueryFlow ? 'show' : 'hidden')}>Select</th>
692                                                        <th scope="col">Name</th>
693                                                        <th scope="col">Description</th>
694                                                        <th scope="col">Category</th>
695                                                        <th scope="col">Creator</th>
696                                                        <th scope="col">Aggregate</th>
697                                                        <th scope="col" className={((type === 'personal') ? '' : 'hidden')}>Shared</th>
698                                                        <th scope="col">Actions</th>
699                                                      </tr>
700                                                    </thead>
701                                                    <tbody>
702                                                    {Object.keys(filteredEntries).sort(function(a, b) {
703                                                                                                       var compareA = a.toUpperCase();
704                                                                                                       var compareB = b.toUpperCase();
705                                                                                                       if(compareA < compareB) return -1;
706                                                                                                       if(compareA > compareB) return 1;
707                                                                                                       return 0;
708                                                                                                      }).map((entry, idx) => {                                                                                                        
709                                                                                                      return (                                                                                                     
710                                                                                                        <tr>
711                                                                                                          <td className={(this.props.isSavedQueryFlow ? '' : 'hidden')}>
712                                                                                                             <div className="checkbox">
713                                                                                                             <OverlayTrigger  placement='top' overlay={<Tooltip id='tooltip-top'>{(this.state.selectedCount===this.state.loadQueryLimit)?'Reached Maximun Template Count '+this.state.loadQueryLimit:(this.state.loadQueryLimit-this.state.selectedCount)+' More Selectable'}</Tooltip>}>
714                                                                                                                             <span className="d-inline-block" style={{display: 'inline-block'}}>                                                                         
715                                                                                                                 <label>
716                                                                                                                     <input type="checkbox" checked={filteredEntries[entry].isSelect} onChange={this.onSelectCheckbox.bind(this)} value={filteredEntries[entry].name + '||' + filteredEntries[entry].description + '||' + filteredEntries[entry].category + '||' + filteredEntries[entry].dsl + '||' + filteredEntries[entry]['is_aggregate'] + '||' +  type + '||' + entry + '||' + filteredEntries[entry]['community_shared'] + '||' + filteredEntries[entry]['template_details']} disabled={!filteredEntries[entry].isSelect && !this.state.loadQueryFlag}/>
717                                                                                                                 </label>
718                                                                                                                 </span>
719                                                                                                             </OverlayTrigger>
720                                                                                                             </div>
721                                                                                                         </td>
722                                                                                                          <td><strong>{filteredEntries[entry].name}</strong></td>
723                                                                                                          <td>{filteredEntries[entry].description}</td>
724                                                                                                          <td width='15%'>{(filteredEntries[entry].category)?filteredEntries[entry].category:''}</td>
725                                                                                                          <td>{filteredEntries[entry].creator}</td>
726                                                                                                          <td>{filteredEntries[entry]['is_aggregate']}</td>
727                                                                                                          <td className={((type === 'personal') ? '' : 'hidden')}>{filteredEntries[entry]['community_shared']}</td>
728                                                                                                          <td className="actionsRow">
729                                                                                                              <div>
730                                                                                                                     <button className={'btn btn-primary ' + (!this.props.isDSLBuilder ? '' : 'hidden')} type='button' value={filteredEntries[entry].dsl + "||" + filteredEntries[entry]['is_aggregate']} onClick={this.loadAndRunQuery}>Run</button>
731                                                                                                                     <button className='btn btn-outline-secondary' type='button' value={filteredEntries[entry].name + '||' + filteredEntries[entry].description + '||' + filteredEntries[entry].category + '||' + filteredEntries[entry].dsl + '||' + filteredEntries[entry]['is_aggregate'] + '||' +  type + '||' + entry + '||' + filteredEntries[entry]['community_shared'] + '||' + filteredEntries[entry]['template_details']  } onClick={this.loadQuery}>Load</button>
732                                                                                                                 <button className={'btn btn-outline-secondary ' + ((this.props.isDataSteward || type === 'personal') && type !== 'community' && !this.props.isDSLBuilder ? '' : 'hidden')} type='button' value={filteredEntries[entry].name + '||' + filteredEntries[entry].description + '||' + filteredEntries[entry].category + '||' + filteredEntries[entry].dsl + '||' + filteredEntries[entry]['is_aggregate'] + '||' +  type +'||' + entry + '||' + filteredEntries[entry]['community_shared'] + '||' + filteredEntries[entry]['template_details']} onClick={this.editSavedQuery}>Edit</button>
733                                                                                                                 <button className={'btn btn-outline-secondary ' + ((this.props.isDataSteward || type === 'personal') && type !== 'community' && !this.props.isDSLBuilder ? '' : 'hidden')} type='button' onClick={(e) => this.openDeleteModal(entry,filteredEntries[entry].name, filteredEntries[entry]['is_public'])}>Delete</button>
734                                                                                                              </div>
735                                                                                                          </td>
736                                                                                                        </tr>
737                                                                                                      );
738                                                                                              })}
739                                                    </tbody>
740                                                  </table>
741                                           </div>
742                                       </div>};
743         let savedQueryMessaging = (type, loadedQueries, queryErrMsg) => { return <Col>
744                                 <Alert className={!queryErrMsg ? 'show' : 'hidden'} bsStyle="warning">
745                                     {type === 'public' && <h3>No Saved Public Queries Loaded</h3>}
746                                     {type === 'community' && <h3>No Saved Community Shared Queries Loaded</h3>}
747                                     {type === 'personal' && <h3>No Saved Personal Queries Loaded</h3>}
748                                 </Alert>
749                                 <Alert bsStyle="danger" className={queryErrMsg ? 'show' : 'hidden'} onDismiss={() => {
750                                                                                                                    if(type==='public'){
751                                                                                                                       this.setState({queriesPublicErrMsg: false});
752                                                                                                                    }else if (type === 'community'){
753                                                                                                                       this.setState({queriesCommunityErrMsg: false});
754                                                                                                                    }else{
755                                                                                                                       this.setState({queriesPersonalErrMsg: false});
756                                                                                                                    }}}>
757                                     <h3>An error occurred</h3>
758                                     <p>
759                                       {queryErrMsg}
760                                     </p>
761                                 </Alert>
762                               </Col>
763         }
764         let savedQueryTabs = () => { return <Tabs defaultActiveKey={'1'} id="multipleTabularView">
765                                                 <Tab eventKey={'1'} title={'Public'}>
766                                                     <Spinner loading={this.state.enablePublicQueriesBusyFeedback}>
767                                                         {Object.keys(this.state.loadedPublicQueries).length <= 0 && (<div>{savedQueryMessaging('public', this.state.loadedPublicQueries, this.state.queriesPublicErrMsg)}</div>)}
768                                                             {Object.keys(this.state.loadedPublicQueries).length > 0 && (<div>{savedQueryCard('public', this.state.totalPublicResults, this.filterPublicList, this.state.filteredPublicEntries)}</div>)}
769                                                         </Spinner>
770                                                     </Tab>
771                                                     <Tab eventKey={'2'} title={'Community'}>
772                                                     <Spinner loading={this.state.enableCommunityQueriesBusyFeedback}>
773                                                         {Object.keys(this.state.loadedCommunityQueries).length <= 0 && (<div>{savedQueryMessaging('community', this.state.loadedCommunityQueries, this.state.queriesCommunityErrMsg)}</div>)}
774                                                         {Object.keys(this.state.loadedCommunityQueries).length > 0 && (<div>{savedQueryCard('community', this.state.totalCommunityResults, this.filterCommunityList, this.state.filteredCommunityEntries)}</div>)}
775                                                     </Spinner>
776                                                 </Tab>
777                                                     <Tab eventKey={'3'} title={'My Personal Queries'}>
778                                                        <Spinner loading={this.state.enablePersonalQueriesBusyFeedback}>
779                                                             {Object.keys(this.state.loadedPersonalQueries).length <= 0 &&(<div>{savedQueryMessaging('personal', this.state.loadedPersonalQueries, this.state.queriesPersonalErrMsg)}</div>)}
780                                                         {Object.keys(this.state.loadedPersonalQueries).length > 0 && (<div>{savedQueryCard('personal', this.state.totalPersonalResults, this.filterPersonalList, this.state.filteredPersonalEntries)}</div>)}
781                                                    </Spinner>
782                                                 </Tab>
783                                            </Tabs>
784         };
785         if (!GlobalExtConstants.INVLIST.IS_ONAP){
786             return (<div>
787             <div className='static-modal'>
788                                 <Modal show={this.state.showDeleteModal} onHide={this.closeDeleteModal} dialogClassName="modal-override">
789                                     <Spinner loading={this.state.enableDeleteBusyFeedback}>
790                                             <Modal.Header>
791                                                 <Modal.Title>Delete DSL Query</Modal.Title>
792                                             </Modal.Header>
793                                             <Modal.Body>
794                                                 <Alert id="deleteError" className={this.state.deleteErrMsg ? 'show' : 'hidden'} bsStyle="danger" onDismiss={() => this.setState({deleteErrMsg: false})}>
795                                             <h3>An error occurred</h3>
796                                             <p>
797                                               {this.state.deleteErrMsg}
798                                             </p>
799                                          </Alert>
800                                         <p>Are you sure you want to delete the following query?: {this.state.focusedEntryName}</p>
801                                             </Modal.Body>
802                                             <Modal.Footer>
803                                         <Button onClick={this.closeDeleteModal}>Cancel</Button>
804                                         <Button onClick={this.submitDelete}>Delete</Button>
805                                     </Modal.Footer>
806                                 </Spinner>
807                                 </Modal>
808             </div>
809
810               <Row>
811                  <Col className={this.props.isSavedQueryFlow ? 'col-lg-10' : 'col-lg-12'}>
812                     <Alert id="deleteSuccess" bsStyle="success" className={this.state.deleteSuccessfulMsg ? 'show' : 'hidden'} onDismiss={() => this.setState({deleteSuccessfulMsg: false})}>
813                             <h3>Delete Successful</h3>
814                             <p>
815                               {this.state.deleteSuccessfulMsg}
816                             </p>
817                     </Alert>
818                     {!this.props.isSavedQueryFlow && (<Panel>
819                       <Panel.Heading>
820                         <Panel.Title toggle>
821                           <div className="checkbox">
822                              <h2>Saved Queries</h2>
823                           </div>
824                         </Panel.Title>
825                       </Panel.Heading>
826                       <Panel.Collapse>
827                         <Panel.Body className='cardwrap'>
828                             {savedQueryTabs()}
829                         </Panel.Body>
830                       </Panel.Collapse>
831                     </Panel>)}
832                     {this.props.isSavedQueryFlow && savedQueryTabs()}
833                   </Col>
834                  </Row>
835           </div>);
836         }else{
837             return (<span></span>);
838         }
839    }
840 }
841
842 export default CustomDSLSaveLoad;