Revert "Renaming Files having BluePrint to have Blueprint"
[ccsdk/cds.git] / cds-ui / client / src / app / feature-modules / blueprint / select-template / search-template / search-template.component.ts
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 { SortPipe } from '../../../../common/shared/pipes/sort.pipe';
32 import { LoaderService } from '../../../../common/core/services/loader.service';
33 import { FormGroup, FormBuilder, Validators } from '@angular/forms';
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   @Input() optionSelected: string;
51   myControl: FormGroup;
52   @Output() resourcesData = new EventEmitter();
53   options: any[] = [];
54   searchText: string = '';
55
56   private paths = [];
57   private tree;
58   private zipFile: JSZip = new JSZip();
59   private fileObject: any;
60   private activationBlueprint: any;
61   private tocsaMetadaData: any;
62   private blueprintName: string;
63   private entryDefinition: string;
64
65   constructor(private store: Store<IAppState>, private loader: LoaderService, private formBuilder: FormBuilder) { }
66
67   ngOnInit() {
68     this.myControl = this.formBuilder.group({
69       search_input: ['', Validators.required]
70     });
71   }
72
73   selected(value) {
74     this.resourcesData.emit(value);
75   }
76
77   fileChanged(e: any) {
78     this.paths = [];
79     this.file = e.target.files[0];
80     this.uploadedFileName = (this.file.name.split('.'))[0];
81     this.zipFile.files = {};
82     this.zipFile.loadAsync(this.file)
83       .then((zip) => {
84         if (zip) {
85           this.loader.showLoader();
86           this.buildFileViewData(zip);
87         }
88       });
89   }
90
91   updateBlueprintState() {
92     let data: IBlueprint = this.activationBlueprint ? JSON.parse(this.activationBlueprint.toString()) : this.activationBlueprint;
93     let blueprintState = {
94       blueprint: data,
95       name: this.blueprintName,
96       files: this.tree,
97       filesData: this.paths,
98       uploadedFileName: this.uploadedFileName,
99       entryDefinition: this.entryDefinition
100     }
101     this.store.dispatch(new SetBlueprintState(blueprintState))
102     
103   }
104
105   async buildFileViewData(zip) {
106     this.validfile = false;
107     this.paths = [];
108     console.log(zip.files);
109     for (var file in zip.files) {
110       console.log("name: " + zip.files[file].name);
111       this.fileObject = {
112         // nameForUIDisplay: this.uploadedFileName + '/' + zip.files[file].name,
113         // name: zip.files[file].name,
114         name: this.uploadedFileName + '/' + zip.files[file].name,
115         data: ''
116       };
117       const value = <any>await zip.files[file].async('string');
118       this.fileObject.data = value;
119       this.paths.push(this.fileObject);
120     }
121
122     if (this.paths) {
123       this.paths.forEach(path => {
124         if (path.name.includes("TOSCA.meta")) {
125           this.validfile = true
126         }
127       });
128     } else {
129       alert('Please update proper file');
130     }
131
132     if (this.validfile) {
133       this.fetchTOSACAMetadata();
134       this.paths = new SortPipe().transform(this.paths, 'asc', 'name');
135       this.tree = this.arrangeTreeData(this.paths);
136     } else {
137       alert('Please update proper file with TOSCA metadata');
138     }
139   }
140
141   arrangeTreeData(paths) {
142     const tree = [];
143
144     paths.forEach((path) => {
145
146       const pathParts = path.name.split('/');
147       // pathParts.shift();
148       let currentLevel = tree;
149
150       pathParts.forEach((part) => {
151         const existingPath = currentLevel.filter(level => level.name === part);
152
153         if (existingPath.length > 0) {
154           currentLevel = existingPath[0].children;
155         } else {
156           const newPart = {
157             name: part,
158             children: [],
159             data: path.data,
160             path: path.name
161           };
162           if (part.trim() == this.blueprintName.trim()) {
163             this.activationBlueprint = path.data;
164             newPart.data = JSON.parse(this.activationBlueprint.toString());
165             console.log('newpart', newPart);
166             this.entryDefinition = path.name.trim();
167           }
168           if (newPart.name !== '') {
169             currentLevel.push(newPart);
170             currentLevel = newPart.children;
171           }
172         }
173       });
174     });
175     this.loader.hideLoader();
176     return tree;
177   }
178
179   fetchTOSACAMetadata() {
180     let toscaData = {};
181     this.paths.forEach(file => {
182       if (file.name.includes('TOSCA.meta')) {
183         let keys = file.data.split("\n");
184         keys.forEach((key) => {
185           let propertyData = key.split(':');
186           toscaData[propertyData[0]] = propertyData[1];
187         });
188       }
189     });
190     this.blueprintName = (((toscaData['Entry-Definitions']).split('/'))[1]).toString();;
191     console.log(toscaData);
192   }
193 }