1 import { Component, EventEmitter, OnDestroy, OnInit, Output, ViewChild, AfterViewInit, ElementRef } 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, Any } from 'json2typescript';
11 import { ToastrService } from 'ngx-toastr';
12 import { Router, ActivatedRoute } from '@angular/router';
13 import { SharedService } from '../shared-service';
16 selector: 'app-templ-mapp-creation',
17 templateUrl: './templ-mapp-creation.component.html',
18 styleUrls: ['./templ-mapp-creation.component.css']
20 export class TemplMappCreationComponent implements OnInit, OnDestroy {
21 @Output() showListViewParent = new EventEmitter<any>();
22 @Output() openList = new EventEmitter<any>();
23 public uploadedFiles: FileSystemFileEntry[] = [];
24 private fileNames: Set<string> = new Set();
25 private jsonConvert = new JsonConvert();
26 public files: NgxFileDropEntry[] = [];
28 templateInfo = new TemplateInfo();
29 variables: string[] = [];
30 dtOptions: DataTables.Settings = {};
31 // We use this trigger because fetching the list of persons can be quite long,
32 // thus we ensure the data is fetched before rendering
33 dtTrigger = new Subject();
34 resTableDtTrigger = new Subject();
35 resourceDictionaryRes: ResourceDictionary[] = [];
36 allowedExt = ['.vtl'];
37 @ViewChild(DataTableDirective, { static: false })
38 dtElement: DataTableDirective;
39 MappingAdapter: MappingAdapter;
41 templateFileContent: string;
42 templateExt = 'Velcoity';
43 dependancies = new Map<string, Array<string>>();
44 dependanciesSource = new Map<string, string>();
51 private packageCreationStore: PackageCreationStore,
52 private templateStore: TemplateStore,
53 private packageCreationUtils: PackageCreationUtils,
54 private toastr: ToastrService,
55 private router: ActivatedRoute,
56 private sharedService: SharedService
61 if (this.router.snapshot.paramMap.has('id')) {
62 console.log('URL contains Id');
63 this.sharedService.enableEdit();
66 this.templateStore.state$.subscribe(templateInfo => {
67 // init Template&mapping vars
68 console.log('Oninit');
69 console.log(templateInfo);
70 this.templateInfo = templateInfo;
71 this.fileName = templateInfo.fileName.split('/')[1];
73 this.fileName = this.fileName.split('-')[0];
75 if (templateInfo.type === 'mapping' || templateInfo.type.includes('mapping')) {
76 this.mappingRes = templateInfo.mapping;
77 this.currentMapping = Object.assign({}, templateInfo);
78 this.resourceDictionaryRes = [];
79 this.resTableDtTrigger.next();
82 this.currentMapping = Any;
84 this.templateFileContent = templateInfo.fileContent;
85 this.currentTemplate = Object.assign({}, templateInfo);
87 if (templateInfo.type === 'template' || templateInfo.type.includes('template')) {
88 this.currentTemplate.fileName = 'Templates/' + this.fileName + '-template.vtl';
90 this.currentTemplate = Any;
95 this.sharedService.isEdit().subscribe(res => {
96 console.log('------------------------');
101 console.log('remove ----');
102 this.currentMapping = {};
103 this.currentTemplate = {};
105 this.templateFileContent = '';
106 this.resourceDictionaryRes = [];
107 this.mappingRes = [];
112 pagingType: 'full_numbers',
120 switch (this.templateExt) {
132 public getTemplateVariable(fileContent: string) {
133 const variables: string[] = [];
134 const stringsSlittedByBraces = fileContent.split('${');
135 const stringsDefaultByDollarSignOnly = fileContent.split('"$');
137 for (let i = 1; i < stringsSlittedByBraces.length; i++) {
138 const element = stringsSlittedByBraces[i];
140 const firstElement = element.split('}')[0];
141 if (!variables.includes(firstElement)) {
142 variables.push(firstElement);
144 console.log(firstElement);
149 for (let i = 1; i < stringsDefaultByDollarSignOnly.length; i++) {
150 const element = stringsDefaultByDollarSignOnly[i];
151 if (element && !element.includes('$')) {
152 const firstElement = element.split('"')[0]
154 .replace('}', '').trim();
155 if (!variables.includes(firstElement)) {
156 variables.push(firstElement);
163 public dropped(files: NgxFileDropEntry[]) {
165 for (const droppedFile of files) {
166 // Is it a file? & Not added before
167 if (droppedFile.fileEntry.isFile && !this.fileNames.has(droppedFile.fileEntry.name)) {
168 const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
169 this.uploadedFiles.push(fileEntry);
170 this.fileNames.add(fileEntry.name);
177 this.dependancies.clear();
178 this.dependanciesSource.clear();
179 if (this.allowedExt.includes('.csv')) {
182 this.setTemplateFilesToStore();
187 for (const droppedFile of this.uploadedFiles) {
188 droppedFile.file((file: File) => {
189 const fileReader = new FileReader();
190 fileReader.onload = (e) => {
191 this.variables = fileReader.result.toString().split(',');
192 console.log(this.variables);
193 this.getMappingTableFromTemplate(null);
195 fileReader.readAsText(file);
198 this.uploadedFiles = [];
201 private convertDictionaryToMap(resourceDictionaries: ResourceDictionary[]): Mapping[] {
202 const mapArray: Mapping[] = [];
203 for (const resourceDictionary of resourceDictionaries) {
204 this.MappingAdapter = new MappingAdapter(resourceDictionary, this.dependancies, this.dependanciesSource);
205 mapArray.push(this.MappingAdapter.ToMapping());
207 console.log(mapArray);
211 setTemplateFilesToStore() {
212 for (const droppedFile of this.uploadedFiles) {
213 droppedFile.file((file: File) => {
214 const fileReader = new FileReader();
215 fileReader.onload = (e) => {
216 this.templateFileContent = fileReader.result.toString();
217 this.variables = this.getTemplateVariable(this.templateFileContent);
220 fileReader.readAsText(file);
223 this.uploadedFiles = [];
226 textChanges(code: any, fileName: string) {
227 // this.packageCreationStore.addTemplate(fileName, code);
228 this.templateFileContent = code;
231 public fileOver(event) {
235 public fileLeave(event) {
239 resetTheUploadedFiles() {
240 this.uploadedFiles = [];
244 this.showListViewParent.emit('tell parent to open create views');
247 closeCreationForm() {
248 this.openList.emit('close create form and open list');
251 getMappingTableFromTemplate(e) {
252 console.log('-' + this.templateFileContent + '-');
253 this.resourceDictionaryRes = [];
257 if (this.variables && this.variables.length > 0) {
259 this.packageCreationStore.getTemplateAndMapping(this.variables).subscribe(res => {
260 let message = 'Attributes are Fetched';
261 this.mappingRes = [];
262 this.resourceDictionaryRes = res;
263 console.log(this.resourceDictionaryRes);
265 if (this.resourceDictionaryRes && this.resourceDictionaryRes.length <= 0) {
266 message = 'No values for those attributes';
268 this.toastr.success(message, 'Success');
270 this.toastr.error('Error');
276 if (!this.dependanciesSource.has(key)) {
277 this.dependanciesSource.set(key, map.key);
283 this.templateFileContent = '';
284 this.resourceDictionaryRes = [];
285 this.mappingRes = [];
286 this.currentMapping = {};
287 this.currentTemplate = {};
288 this.closeCreationForm();
292 // check file duplication
293 console.log('----------- mode ' + this.edit);
295 (!(this.packageCreationStore.fileExist('Templates/' + this.fileName + '-mapping.json')
296 || this.packageCreationStore.fileExist('Templates/' + this.fileName + '-template' + this.getFileExtension())))
299 // Save Mapping to Store
300 if (this.resourceDictionaryRes && this.resourceDictionaryRes.length > 0) {
301 const mapArray = this.convertDictionaryToMap(this.resourceDictionaryRes);
302 this.packageCreationStore.addMapping('Templates/' + this.fileName + '-mapping.json',
303 this.packageCreationUtils.transformToJson(this.jsonConvert.serialize(mapArray)));
304 this.resourceDictionaryRes = [];
306 // Save Template to store
307 if (this.templateFileContent) {
308 this.packageCreationStore.addTemplate('Templates/' + this.fileName + '-template' + this.getFileExtension(),
309 this.templateFileContent);
310 this.templateFileContent = '';
313 this.toastr.success('File is created', 'success');
314 this.closeCreationForm();
316 console.log('this file already exist');
317 this.toastr.error('File name already exist', 'Error');
320 this.toastr.error('Add the file name', 'Error');
325 selectSource(dict, e) {
326 const source = e.target.value;
327 let keyDepend = null;
329 keyDepend = dict.definition.sources[source].properties['key-dependencies'] || null;
334 this.dependancies.set(dict.name, keyDepend);
336 // this.dependancies.delete(dict.name);
337 // this.dependanciesSource.delete(dict.name);
339 this.dependanciesSource.set(dict.name, source);
340 console.log(this.dependancies);
341 console.log(this.dependanciesSource);
344 getKeys(map: Map<string, any>) {
345 return Array.from(map.keys());
349 return this.dependancies.get(key);
353 if (this.dtElement.dtInstance) {
354 console.log('rerender');
355 this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
356 dtInstance.destroy();
357 this.dtElement.dtOptions = this.dtOptions;
358 this.dtElement.dtTrigger.next();
362 this.dtTrigger.next();
366 ngOnDestroy(): void {
367 // Do not forget to unsubscribe the event
368 this.dtTrigger.unsubscribe();
372 class DependancyVal {
379 this.source = source;
380 this.keyDepend = keyDepend;