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