4ab96ee3cb8eca08a171d674afe8146ec571aaf2
[ccsdk/cds.git] /
1 import { Component, EventEmitter, OnInit, Output, OnDestroy, 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 { MappingAdapter, Mapping } 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': return '.vtl';
67             case 'Koltin': return '.ktl';
68             case 'Jinja': return '.j2';
69             default: return '.vtl';
70         }
71     }
72     public getTemplateVariable(fileContent: string) {
73         const variables: string[] = [];
74         const stringsSlittedByBraces = fileContent.split('${');
75         const stringsDefaultByDollarSignOnly = fileContent.split('"$');
76
77         for (let i = 1; i < stringsSlittedByBraces.length; i++) {
78             const element = stringsSlittedByBraces[i];
79             if (element) {
80                 const firstElement = element.split('}')[0];
81                 if (!variables.includes(firstElement)) {
82                     variables.push(firstElement);
83                 } else {
84                     console.log(firstElement);
85                 }
86             }
87         }
88
89         for (let i = 1; i < stringsDefaultByDollarSignOnly.length; i++) {
90             const element = stringsDefaultByDollarSignOnly[i];
91             if (element && !element.includes('$')) {
92                 const firstElement = element.split('"')[0]
93                     .replace('{', '')
94                     .replace('}', '').trim();
95                 if (!variables.includes(firstElement)) {
96                     variables.push(firstElement);
97                 }
98             }
99         }
100         return variables;
101     }
102
103     public dropped(files: NgxFileDropEntry[]) {
104         this.files = files;
105         for (const droppedFile of files) {
106             // Is it a file? & Not added before
107             if (droppedFile.fileEntry.isFile && !this.fileNames.has(droppedFile.fileEntry.name)) {
108                 const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
109                 this.uploadedFiles.push(fileEntry);
110                 this.fileNames.add(fileEntry.name);
111
112             }
113         }
114     }
115
116     removeFile(fileIndex: number) {
117         /*const filename = 'Definitions/' + this.uploadedFiles[fileIndex].name;
118         this.packageCreationStore.removeFileFromDefinition(filename);
119         this.uploadedFiles.splice(fileIndex, 1);*/
120     }
121
122     uploadFile() {
123         if (this.allowedExt.includes('.csv')) {
124             this.fetchCSVkeys();
125         } else {
126             this.setTemplateFilesToStore();
127         }
128     }
129
130     fetchCSVkeys() {
131         for (const droppedFile of this.uploadedFiles) {
132             droppedFile.file((file: File) => {
133                 const fileReader = new FileReader();
134                 fileReader.onload = (e) => {
135                     this.variables = fileReader.result.toString().split(',');
136                     console.log(this.variables);
137                     this.getMappingTableFromTemplate(null);
138                 };
139                 fileReader.readAsText(file);
140             });
141         }
142         this.uploadedFiles = [];
143     }
144
145     private convertDictionaryToMap(resourceDictionaries: ResourceDictionary[]): Mapping[] {
146         const mapArray: Mapping[] = [];
147         for (const resourceDictionary of resourceDictionaries) {
148             this.MappingAdapter = new MappingAdapter(resourceDictionary);
149             mapArray.push(this.MappingAdapter.ToMapping());
150         }
151         console.log(mapArray);
152         return mapArray;
153     }
154
155     setTemplateFilesToStore() {
156         for (const droppedFile of this.uploadedFiles) {
157             droppedFile.file((file: File) => {
158                 const fileReader = new FileReader();
159                 fileReader.onload = (e) => {
160                     this.templateFileContent = fileReader.result.toString();
161                     this.variables = this.getTemplateVariable(this.templateFileContent);
162
163                 };
164                 fileReader.readAsText(file);
165             });
166         }
167         this.uploadedFiles = [];
168     }
169
170     textChanges(code: any, fileName: string) {
171         //  this.packageCreationStore.addTemplate(fileName, code);
172         this.templateFileContent = code;
173     }
174
175     public fileOver(event) {
176         console.log(event);
177     }
178
179     public fileLeave(event) {
180         console.log(event);
181     }
182
183     resetTheUploadedFiles() {
184         this.uploadedFiles = [];
185     }
186
187     openListView() {
188         this.showListViewParent.emit('tell parent to open create views');
189     }
190
191     getMappingTableFromTemplate(e) {
192         if (e) { e.preventDefault(); }
193         if (this.variables && this.variables.length > 0) {
194             console.log('base');
195             this.packageCreationStore.getTemplateAndMapping(this.variables).subscribe(res => {
196                 this.resourceDictionaryRes = res;
197                 console.log(this.resourceDictionaryRes);
198                 this.rerender();
199             });
200         }
201     }
202
203     saveToStore() {
204         if (this.fileName) {
205             // Save Mapping to Store
206             if (this.resourceDictionaryRes) {
207                 const mapArray = this.convertDictionaryToMap(this.resourceDictionaryRes);
208                 this.packageCreationStore.addMapping('Templates/' + this.fileName + '-mapping.json',
209                     this.packageCreationUtils.transformToJson(this.jsonConvert.serialize(mapArray)));
210             }
211             // Save Template to store
212             if (this.templateFileContent) {
213                 this.packageCreationStore.addTemplate('Templates/' + this.fileName + '-template' + this.getFileExtension(),
214                     this.templateFileContent);
215             }
216         } else {
217
218         }
219     }
220
221     rerender(): void {
222         if (this.dtElement.dtInstance) {
223             console.log('rerender');
224             this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
225                 dtInstance.destroy();
226                 this.dtElement.dtOptions = this.dtOptions;
227                 this.dtElement.dtTrigger.next();
228                 dtInstance.draw();
229             });
230         } else {
231             this.dtTrigger.next();
232         }
233     }
234
235     ngOnDestroy(): void {
236         // Do not forget to unsubscribe the event
237         this.dtTrigger.unsubscribe();
238     }
239 }