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