ce7d5aac2d8a9caea00502f41b6eb3dc9f1bd2d6
[ccsdk/cds.git] /
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018 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, EventEmitter, Output, ViewChild, Input } from '@angular/core';
23 import { Store } from '@ngrx/store';
24 import * as JSZip from 'jszip';
25 import { Observable } from 'rxjs';
26
27 import { IBlueprint } from '../../../../common/core/store/models/blueprint.model';
28 import { IBlueprintState } from '../../../../common/core/store/models/blueprintState.model';
29 import { IAppState } from '../../../../common/core/store/state/app.state';
30 import { LoadBlueprintSuccess, SET_BLUEPRINT_STATE, SetBlueprintState } from '../../../../common/core/store/actions/blueprint.action';
31 import { json } from 'd3';
32 import { SortPipe } from '../../../../common/shared/pipes/sort.pipe';
33 import { LoaderService } from '../../../../common/core/services/loader.service';
34 import { FormGroup, FormBuilder, Validators } from '@angular/forms';
35 import { MatAutocompleteTrigger } from '@angular/material';
36
37
38 @Component({
39   selector: 'app-search-template',
40   templateUrl: './search-template.component.html',
41   styleUrls: ['./search-template.component.scss']
42 })
43 export class SearchTemplateComponent implements OnInit {
44   file: File;
45   localBluePrintData: IBlueprint;
46   fileText: object[];
47   blueprintState: IBlueprintState;
48   bpState: Observable<IBlueprintState>;
49   validfile: boolean = false;
50   uploadedFileName: string;
51   @ViewChild('fileInput') fileInput;
52   result: string = '';
53   @Input() optionSelected: string;
54   myControl: FormGroup;
55   @ViewChild('resourceSelect', { read: MatAutocompleteTrigger }) resourceSelect: MatAutocompleteTrigger;
56   @Output() resourcesData = new EventEmitter();
57   options: any[]   = [];
58   searchText: string = '';
59
60   private paths = [];
61   private tree;
62   private zipFile: JSZip = new JSZip();
63   private fileObject: any;
64   private activationBlueprint: any;
65   private tocsaMetadaData: any;
66   private blueprintName: string;
67   private entryDefinition: string;
68
69   constructor(private store: Store<IAppState>, private loader: LoaderService,private formBuilder: FormBuilder) { }
70
71   ngOnInit() {
72     this.myControl = this.formBuilder.group({
73       search_input: ['', Validators.required]
74     });
75   }
76
77   selected(value) {
78     this.resourcesData.emit(value);
79   }
80
81   fetchResourceByName() {
82     // this.exsistingModelService.searchByTags(this.searchText)
83     //   .subscribe(data => {
84     //     console.log(data);
85     //     data.forEach(element => {
86     //       this.options.push(element)
87     //     });
88     //     this.resourceSelect.openPanel();
89     //   }, error => {
90     //     window.alert('error' + error);
91     //   })
92   }
93   fileChanged(e: any) {
94     this.paths = [];
95     this.file = e.target.files[0];
96     this.uploadedFileName = (this.file.name.split('.'))[0];
97     this.zipFile.files = {};
98     this.zipFile.loadAsync(this.file)
99       .then((zip) => {
100         if(zip) { 
101           this.loader.showLoader();           
102           this.buildFileViewData(zip);
103         }
104       });
105   }
106
107   updateBlueprintState() {
108     let data: IBlueprint = this.activationBlueprint ? JSON.parse(this.activationBlueprint.toString()) : this.activationBlueprint;
109     let blueprintState = {
110       blueprint: data,
111       name: this.blueprintName,
112       files: this.tree,
113       filesData: this.paths,
114       uploadedFileName: this.uploadedFileName,
115       entryDefinition: this.entryDefinition
116     }
117     this.store.dispatch(new SetBlueprintState(blueprintState))
118     // this.store.dispatch(new LoadBlueprintSuccess(data));
119   }
120
121   async buildFileViewData(zip) {
122     this.validfile = false;
123     this.paths = [];
124     console.log(zip.files);
125     for (var file in zip.files) {
126       console.log("name: " +zip.files[file].name);
127       this.fileObject = {
128         // nameForUIDisplay: this.uploadedFileName + '/' + zip.files[file].name,
129         // name: zip.files[file].name,
130         name: this.uploadedFileName + '/' + zip.files[file].name,
131         data: ''
132       };
133       const value = <any>await  zip.files[file].async('string');
134       this.fileObject.data = value;
135       this.paths.push(this.fileObject); 
136     }
137
138     if(this.paths) {
139       this.paths.forEach(path =>{
140         if(path.name.includes("TOSCA.meta")) {
141           this.validfile = true
142         }
143       });
144     } else {
145       alert('Please update proper file');
146     }
147
148     if(this.validfile) {      
149       this.fetchTOSACAMetadata();
150       this.paths = new SortPipe().transform(this.paths, 'asc', 'name');
151       this.tree = this.arrangeTreeData(this.paths);
152     } else {
153       alert('Please update proper file with TOSCA metadata');
154     }
155   }
156
157   arrangeTreeData(paths) {
158     const tree = [];
159
160     paths.forEach((path) => {
161
162       const pathParts = path.name.split('/');
163       // pathParts.shift();
164       let currentLevel = tree;
165
166       pathParts.forEach((part) => {
167         const existingPath = currentLevel.filter(level => level.name === part);
168
169         if (existingPath.length > 0) {
170           currentLevel = existingPath[0].children;
171         } else {
172           const newPart = {
173             name: part,
174             children: [],
175             data: path.data,
176             path : path.name
177           };
178           if(part.trim() == this.blueprintName.trim()) { 
179             this.activationBlueprint = path.data; 
180             newPart.data = JSON.parse(this.activationBlueprint.toString());            
181             console.log('newpart', newPart);
182             this.entryDefinition = path.name.trim();
183           }
184           if(newPart.name !== '') {            
185               currentLevel.push(newPart);
186               currentLevel = newPart.children;
187           }
188         }
189       });
190     });    
191     this.loader.hideLoader();
192     return tree;
193   }
194
195   fetchTOSACAMetadata() {
196     let toscaData = {};
197     this.paths.forEach(file =>{
198       if(file.name.includes('TOSCA.meta')) {
199         let keys = file.data.split("\n");
200         keys.forEach((key)=>{
201           let propertyData = key.split(':');
202           toscaData[propertyData[0]] = propertyData[1];
203         });
204       }
205     });
206     this.blueprintName = (((toscaData['Entry-Definitions']).split('/'))[1]).toString();;
207     console.log(toscaData);
208   }
209 }