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