Edit CBA method integration
[ccsdk/cds.git] / cds-ui / client / src / app / feature-modules / blueprint / select-template / search-template / search-from-database / search-from-database.component.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2019 IBM Intellectual Property. All rights reserved.
5 ===================================================================
6
7 Unless otherwise specified, all software contained herein is licensed
8 under the Apache License, Version 2.0 (the License);
9 you may not use this software except in compliance with the License.
10 You may obtain a copy of the License at
11
12     http://www.apache.org/licenses/LICENSE-2.0
13
14 Unless required by applicable law or agreed to in writing, software
15 distributed under the License is distributed on an "AS IS" BASIS,
16 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 See the License for the specific language governing permissions and
18 limitations under the License.
19 ============LICENSE_END============================================
20 */
21
22 import { Component, OnInit, ViewChild, EventEmitter, Output } from '@angular/core';
23 import { FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { Store } from '@ngrx/store';
25 import { SearchTemplateService } from '../search-template.service';
26 import { MatAutocompleteTrigger } from '@angular/material';
27 import { NotificationHandlerService } from 'src/app/common/core/services/notification-handler.service';
28 import { SearchPipe } from 'src/app/common/shared/pipes/search.pipe';
29 import * as JSZip from 'jszip';
30 import { SortPipe } from '../../../../../common/shared/pipes/sort.pipe';
31 import { LoaderService } from '../../../../../common/core/services/loader.service';
32 import { IBlueprint } from '../../../../../common/core/store/models/blueprint.model';
33 import { IBlueprintState } from '../../../../../common/core/store/models/blueprintState.model';
34 import { IAppState } from '../../../../../common/core/store/state/app.state';
35 import { SetBlueprintState } from '../../../../../common/core/store/actions/blueprint.action';
36
37 @Component({
38   selector: 'app-search-from-database',
39   templateUrl: './search-from-database.component.html',
40   styleUrls: ['./search-from-database.component.scss']
41 })
42 export class SearchFromDatabaseComponent implements OnInit {
43
44   myControl: FormGroup;
45   @Output() resourcesData = new EventEmitter();
46   options: any[] = [];
47   // @ViewChild('resourceSelect', { read: MatAutocompleteTrigger }) resourceSelect: MatAutocompleteTrigger;
48
49   validfile: boolean = false;
50   filesTree: any = [];
51   filesData: any = [];
52   private zipFile: JSZip = new JSZip();
53   private paths = [];
54   private tree;
55   private fileObject: any;
56   private activationBlueprint: any;
57   private tocsaMetadaData: any;
58   private blueprintName: string;
59   private entryDefinition: string;
60   uploadedFileName: string;
61
62   searchText: string = '';
63   constructor(private _formBuilder: FormBuilder,
64     private searchService: SearchTemplateService, private alertService: NotificationHandlerService, 
65     private loader: LoaderService, private store: Store<IAppState>) { }
66
67   ngOnInit() {
68     this.myControl = this._formBuilder.group({
69       search_input: ['', Validators.required]
70     });
71   }
72   selected(value) {
73     this.resourcesData.emit(value);
74   }
75
76   fetchResourceByName() {
77     this.options = [];
78     this.searchService.searchByTags(this.searchText)
79       .subscribe(data => {
80         data.forEach(element => {
81           this.options.push(element)
82         });
83       }, error => {
84         this.alertService.error('Blueprint not matching the search tag' + error);
85       })
86   }
87
88   editCBA(artifactName: string,artifactVersion:string, option: string) {
89     this.zipFile.generateAsync({ type: "blob" })
90       .then(blob => {
91         const formData = new FormData();
92         formData.append("file", blob);
93         // this.editorService.enrich("/enrich-blueprint/", formData)
94         this.searchService.getBlueprintZip(artifactName + "/" + artifactVersion)
95           .subscribe(
96             (response) => {
97               // console.log(response);
98               this.zipFile.files = {};
99               this.zipFile.loadAsync(response)
100                 .then((zip) => {
101                   if (zip) {
102                     this.buildFileViewData(zip);
103                     // console.log("processed");
104                     let data: IBlueprint = this.activationBlueprint ? JSON.parse(this.activationBlueprint.toString()) : this.activationBlueprint;
105                     let blueprintState = {
106                       blueprint: data,
107                       name: this.blueprintName,
108                       files: this.tree,
109                       filesData: this.paths,
110                       uploadedFileName: this.blueprintName,
111                       entryDefinition: this.entryDefinition
112                     }
113                     this.store.dispatch(new SetBlueprintState(blueprintState));
114                     // console.log(blueprintState);
115                   }
116                 });
117               // this.alertService.success('Blueprint enriched successfully');
118             },
119             (error) => {
120               this.alertService.error('Blue print error' + error.message);
121             });
122       });
123   }
124
125   create() {
126     this.filesData.forEach((path) => {
127       let index = path.name.indexOf("/");
128       let name = path.name.slice(index + 1, path.name.length);
129       this.zipFile.file(name, path.data);
130     });
131   }
132
133   async buildFileViewData(zip) {
134     this.validfile = false;
135     this.paths = [];
136     // console.log(zip.files);
137     for (var file in zip.files) {
138       console.log("name: " + zip.files[file].name);
139       this.fileObject = {
140         // nameForUIDisplay: this.uploadedFileName + '/' + zip.files[file].name,
141         // name: zip.files[file].name,
142         name: this.uploadedFileName + '/' + zip.files[file].name,
143         data: ''
144       };
145       const value = <any>await zip.files[file].async('string');
146       this.fileObject.data = value;
147       this.paths.push(this.fileObject);
148     }
149
150     if (this.paths) {
151       this.paths.forEach(path => {
152         if (path.name.includes("TOSCA.meta")) {
153           this.validfile = true
154         }
155       });
156     } else {
157       alert('Please update proper file');
158     }
159
160     if (this.validfile) {
161       this.fetchTOSACAMetadata();
162       this.paths = new SortPipe().transform(this.paths, 'asc', 'name');
163       this.tree = this.arrangeTreeData(this.paths);
164     } else {
165       alert('Please update proper file with TOSCA metadata');
166     }
167   }
168
169   arrangeTreeData(paths) {
170     const tree = [];
171
172     paths.forEach((path) => {
173
174       const pathParts = path.name.split('/');
175       // pathParts.shift();
176       let currentLevel = tree;
177
178       pathParts.forEach((part) => {
179         const existingPath = currentLevel.filter(level => level.name === part);
180
181         if (existingPath.length > 0) {
182           currentLevel = existingPath[0].children;
183         } else {
184           const newPart = {
185             name: part,
186             children: [],
187             data: path.data,
188             path: path.name
189           };
190           if (part.trim() == this.blueprintName.trim()) {
191             this.activationBlueprint = path.data;
192             newPart.data = JSON.parse(this.activationBlueprint.toString());
193             // console.log('newpart', newPart);
194             this.entryDefinition = path.name.trim();
195           }
196           if (newPart.name !== '') {
197             currentLevel.push(newPart);
198             currentLevel = newPart.children;
199           }
200         }
201       });
202     });
203     this.loader.hideLoader();
204     return tree;
205   }
206
207   fetchTOSACAMetadata() {
208     let toscaData = {};
209     this.paths.forEach(file => {
210       if (file.name.includes('TOSCA.meta')) {
211         let keys = file.data.split("\n");
212         keys.forEach((key) => {
213           let propertyData = key.split(':');
214           toscaData[propertyData[0]] = propertyData[1];
215         });
216       }
217     });
218     this.blueprintName = (((toscaData['Entry-Definitions']).split('/'))[1]).toString();;
219     // console.log(toscaData);
220   }
221 }