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