1514392ed1ac28e9578cef98d5f69e876de734d4
[ccsdk/cds.git] /
1 import {Component, EventEmitter, OnDestroy, OnInit, Output, ViewChild} from '@angular/core';
2 import {FileSystemFileEntry, NgxFileDropEntry} from 'ngx-file-drop';
3 import {PackageCreationStore} from '../../package-creation.store';
4 import {TemplateInfo, TemplateStore} from '../../template.store';
5 import {Subject} from 'rxjs';
6 import {ResourceDictionary} from '../../mapping-models/ResourceDictionary.model';
7 import {DataTableDirective} from 'angular-datatables';
8 import {Mapping, MappingAdapter} from '../../mapping-models/mappingAdapter.model';
9 import {PackageCreationUtils} from '../../package-creation.utils';
10 import {JsonConvert} from 'json2typescript';
11
12 @Component({
13     selector: 'app-templ-mapp-creation',
14     templateUrl: './templ-mapp-creation.component.html',
15     styleUrls: ['./templ-mapp-creation.component.css']
16 })
17 export class TemplMappCreationComponent implements OnInit, OnDestroy {
18     @Output() showListViewParent = new EventEmitter<any>();
19
20     public uploadedFiles: FileSystemFileEntry[] = [];
21     private fileNames: Set<string> = new Set();
22     private jsonConvert = new JsonConvert();
23     public files: NgxFileDropEntry[] = [];
24     fileName: any;
25     templateInfo = new TemplateInfo();
26     private variables: string[] = [];
27     private mappingFileValues = [];
28     dtOptions: DataTables.Settings = {};
29     // We use this trigger because fetching the list of persons can be quite long,
30     // thus we ensure the data is fetched before rendering
31     dtTrigger = new Subject();
32     resourceDictionaryRes: ResourceDictionary[] = [];
33     allowedExt = ['.vtl'];
34     @ViewChild(DataTableDirective, {static: false})
35     dtElement: DataTableDirective;
36     MappingAdapter: MappingAdapter;
37     mapping = new Map();
38     templateFileContent: string;
39     templateExt = 'Velcoity';
40
41
42     constructor(
43         private packageCreationStore: PackageCreationStore,
44         private templateStore: TemplateStore,
45         private packageCreationUtils: PackageCreationUtils
46     ) {
47     }
48
49     ngOnInit() {
50         this.templateStore.state$.subscribe(templateInfo => {
51             console.log(templateInfo);
52             this.templateInfo = templateInfo;
53             this.fileName = templateInfo.fileName.split('/')[1];
54         });
55
56         this.dtOptions = {
57             pagingType: 'full_numbers',
58             pageLength: 10,
59             destroy: true,
60             // retrieve: true,
61         };
62     }
63
64     getFileExtension() {
65         switch (this.templateExt) {
66             case 'Velcoity':
67                 return '.vtl';
68             case 'Koltin':
69                 return '.ktl';
70             case 'Jinja':
71                 return '.j2';
72             default:
73                 return '.vtl';
74         }
75     }
76
77     public getTemplateVariable(fileContent: string) {
78         const variables: string[] = [];
79         const stringsSlittedByBraces = fileContent.split('${');
80         const stringsDefaultByDollarSignOnly = fileContent.split('"$');
81
82         for (let i = 1; i < stringsSlittedByBraces.length; i++) {
83             const element = stringsSlittedByBraces[i];
84             if (element) {
85                 const firstElement = element.split('}')[0];
86                 if (!variables.includes(firstElement)) {
87                     variables.push(firstElement);
88                 } else {
89                     console.log(firstElement);
90                 }
91             }
92         }
93
94         for (let i = 1; i < stringsDefaultByDollarSignOnly.length; i++) {
95             const element = stringsDefaultByDollarSignOnly[i];
96             if (element && !element.includes('$')) {
97                 const firstElement = element.split('"')[0]
98                     .replace('{', '')
99                     .replace('}', '').trim();
100                 if (!variables.includes(firstElement)) {
101                     variables.push(firstElement);
102                 }
103             }
104         }
105         return variables;
106     }
107
108     public dropped(files: NgxFileDropEntry[]) {
109         this.files = files;
110         for (const droppedFile of files) {
111             // Is it a file? & Not added before
112             if (droppedFile.fileEntry.isFile && !this.fileNames.has(droppedFile.fileEntry.name)) {
113                 const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
114                 this.uploadedFiles.push(fileEntry);
115                 this.fileNames.add(fileEntry.name);
116
117             }
118         }
119     }
120
121     uploadFile() {
122         if (this.allowedExt.includes('.csv')) {
123             this.fetchCSVkeys();
124         } else {
125             this.setTemplateFilesToStore();
126         }
127     }
128
129     fetchCSVkeys() {
130         for (const droppedFile of this.uploadedFiles) {
131             droppedFile.file((file: File) => {
132                 const fileReader = new FileReader();
133                 fileReader.onload = (e) => {
134                     this.variables = fileReader.result.toString().split(',');
135                     console.log(this.variables);
136                     this.getMappingTableFromTemplate(null);
137                 };
138                 fileReader.readAsText(file);
139             });
140         }
141         this.uploadedFiles = [];
142     }
143
144     private convertDictionaryToMap(resourceDictionaries: ResourceDictionary[]): Mapping[] {
145         const mapArray: Mapping[] = [];
146         for (const resourceDictionary of resourceDictionaries) {
147             this.MappingAdapter = new MappingAdapter(resourceDictionary);
148             mapArray.push(this.MappingAdapter.ToMapping());
149         }
150         console.log(mapArray);
151         return mapArray;
152     }
153
154     setTemplateFilesToStore() {
155         for (const droppedFile of this.uploadedFiles) {
156             droppedFile.file((file: File) => {
157                 const fileReader = new FileReader();
158                 fileReader.onload = (e) => {
159                     this.templateFileContent = fileReader.result.toString();
160                     this.variables = this.getTemplateVariable(this.templateFileContent);
161
162                 };
163                 fileReader.readAsText(file);
164             });
165         }
166         this.uploadedFiles = [];
167     }
168
169     textChanges(code: any, fileName: string) {
170         //  this.packageCreationStore.addTemplate(fileName, code);
171         this.templateFileContent = code;
172     }
173
174     public fileOver(event) {
175         console.log(event);
176     }
177
178     public fileLeave(event) {
179         console.log(event);
180     }
181
182     resetTheUploadedFiles() {
183         this.uploadedFiles = [];
184     }
185
186     openListView() {
187         this.showListViewParent.emit('tell parent to open create views');
188     }
189
190     getMappingTableFromTemplate(e) {
191         if (e) {
192             e.preventDefault();
193         }
194         if (this.variables && this.variables.length > 0) {
195             console.log('base');
196             this.packageCreationStore.getTemplateAndMapping(this.variables).subscribe(res => {
197                 this.resourceDictionaryRes = res;
198                 console.log(this.resourceDictionaryRes);
199                 this.rerender();
200             });
201         }
202     }
203
204     saveToStore() {
205         if (this.fileName) {
206             // Save Mapping to Store
207             if (this.resourceDictionaryRes && this.resourceDictionaryRes.length > 0) {
208                 const mapArray = this.convertDictionaryToMap(this.resourceDictionaryRes);
209                 this.packageCreationStore.addMapping('Templates/' + this.fileName + '-mapping.json',
210                     this.packageCreationUtils.transformToJson(this.jsonConvert.serialize(mapArray)));
211                 this.resourceDictionaryRes = [];
212             }
213             // Save Template to store
214             if (this.templateFileContent) {
215                 this.packageCreationStore.addTemplate('Templates/' + this.fileName + '-template' + this.getFileExtension(),
216                     this.templateFileContent);
217                 this.templateFileContent = '';
218             }
219         } else {
220
221         }
222     }
223
224     rerender(): void {
225         if (this.dtElement.dtInstance) {
226             console.log('rerender');
227             this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
228                 dtInstance.destroy();
229                 this.dtElement.dtOptions = this.dtOptions;
230                 this.dtElement.dtTrigger.next();
231                 dtInstance.draw();
232             });
233         } else {
234             this.dtTrigger.next();
235         }
236     }
237
238     ngOnDestroy(): void {
239         // Do not forget to unsubscribe the event
240         this.dtTrigger.unsubscribe();
241     }
242 }