1d0ba2c39d6ea5d5aa14f28f6f68780b064fd409
[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 } 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
33 @Component({
34   selector: 'app-search-template',
35   templateUrl: './search-template.component.html',
36   styleUrls: ['./search-template.component.scss']
37 })
38 export class SearchTemplateComponent implements OnInit {
39   file: File;
40   localBluePrintData: IBlueprint;
41   fileText: object[];
42   blueprintState: IBlueprintState;
43   bpState: Observable<IBlueprintState>;
44   validfile: boolean = false;
45   uploadedFileName: string;
46   @ViewChild('fileInput') fileInput;
47   result: string = '';
48
49   private paths = [];
50   private tree;
51   private zipFile: JSZip = new JSZip();
52   private fileObject: any;
53   private activationBlueprint: any;
54   private tocsaMetadaData: any;
55   private blueprintName: string;
56
57   constructor(private store: Store<IAppState>) { }
58
59   ngOnInit() {
60   }
61
62   fileChanged(e: any) {
63     this.paths = [];
64     this.file = e.target.files[0];
65     this.uploadedFileName = (this.file.name.split('.'))[0];
66     this.zipFile.files = {};
67     this.zipFile.loadAsync(this.file)
68       .then((zip) => {
69         if(zip) {            
70           this.buildFileViewData(zip);
71         }
72       });
73   }
74
75   updateBlueprintState() {
76     let data: IBlueprint = this.activationBlueprint ? JSON.parse(this.activationBlueprint.toString()) : this.activationBlueprint;
77     let blueprintState = {
78       blueprint: data,
79       name: this.blueprintName,
80       files: this.tree,
81       filesData: this.paths,
82       uploadedFileName: this.uploadedFileName
83     }
84     this.store.dispatch(new SetBlueprintState(blueprintState))
85     // this.store.dispatch(new LoadBlueprintSuccess(data));
86   }
87
88   async buildFileViewData(zip) {
89     this.validfile = false;
90     this.paths = [];
91     console.log(zip.files);
92     for (var file in zip.files) {
93       console.log("name: " +zip.files[file].name);
94       this.fileObject = {
95         // nameForUIDisplay: this.uploadedFileName + '/' + zip.files[file].name,
96         // name: zip.files[file].name,
97         name: this.uploadedFileName + '/' + zip.files[file].name,
98         data: ''
99       };
100       const value = <any>await  zip.files[file].async('string');
101       this.fileObject.data = value;
102       this.paths.push(this.fileObject); 
103     }
104
105     if(this.paths) {
106       this.paths.forEach(path =>{
107         if(path.name.includes("TOSCA.meta")) {
108           this.validfile = true
109         }
110       });
111     } else {
112       alert('Please update proper file');
113     }
114
115     if(this.validfile) {      
116       this.fetchTOSACAMetadata();
117       this.tree = this.arrangeTreeData(this.paths);
118     } else {
119       alert('Please update proper file with TOSCA metadata');
120     }
121   }
122
123   arrangeTreeData(paths) {
124     const tree = [];
125
126     paths.forEach((path) => {
127
128       const pathParts = path.name.split('/');
129       // pathParts.shift();
130       let currentLevel = tree;
131
132       pathParts.forEach((part) => {
133         const existingPath = currentLevel.filter(level => level.name === part);
134
135         if (existingPath.length > 0) {
136           currentLevel = existingPath[0].children;
137         } else {
138           const newPart = {
139             name: part,
140             children: [],
141             data: path.data,
142             path : path.name
143           };
144           if(part.trim() == this.blueprintName.trim()) { 
145             this.activationBlueprint = path.data; 
146             newPart.data = JSON.parse(this.activationBlueprint.toString());            
147             console.log('newpart', newPart);
148           }
149           if(newPart.name !== '') {            
150               currentLevel.push(newPart);
151               currentLevel = newPart.children;
152           }
153         }
154       });
155     });
156     console.log('tree', tree);
157     return tree;
158   }
159
160   fetchTOSACAMetadata() {
161     let toscaData = {};
162     this.paths.forEach(file =>{
163       if(file.name.includes('TOSCA.meta')) {
164         let keys = file.data.split("\n");
165         keys.forEach((key)=>{
166           let propertyData = key.split(':');
167           toscaData[propertyData[0]] = propertyData[1];
168         });
169       }
170     });
171     this.blueprintName = (((toscaData['Entry-Definitions']).split('/'))[1]).toString();;
172     console.log(toscaData);
173   }
174 }