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, Any } from 'json2typescript';
11 import { ToastrService } from 'ngx-toastr';
12 import { SharedService } from '../shared-service';
13 import { XmlParser } from '../utils/ParserFactory/XmlParser';
14 import { TourService } from 'ngx-tour-md-menu';
15 import { PackageCreationService } from '../../package-creation.service';
16 import { ParserFactory } from '../utils/ParserFactory/ParserFactory';
17 import { TemplateType, FileExtension } from '../utils/TemplateType';
21 selector: 'app-templ-mapp-creation',
22 templateUrl: './templ-mapp-creation.component.html',
23 styleUrls: ['./templ-mapp-creation.component.css']
25 export class TemplMappCreationComponent implements OnInit, OnDestroy {
26 @Output() showListView = new EventEmitter<any>();
27 @Output() showCreationView = new EventEmitter<any>();
28 public uploadedFiles: FileSystemFileEntry[] = [];
29 fileNames: Set<string> = new Set();
30 jsonConvert = new JsonConvert();
31 public files: NgxFileDropEntry[] = [];
33 templateInfo = new TemplateInfo();
34 variables: string[] = [];
35 dtOptions: DataTables.Settings = {};
36 initDtOptions: DataTables.Settings = {};
37 // We use this trigger because fetching the list of persons can be quite long,
38 // thus we ensure the data is fetched before rendering
39 dtTrigger = new Subject();
40 resTableDtTrigger = new Subject();
41 resourceDictionaryRes: ResourceDictionary[] = [];
42 allowedExt = ['.vtl'];
43 @ViewChild(DataTableDirective, { static: false })
44 dtElement: DataTableDirective;
45 MappingAdapter: MappingAdapter;
47 templateFileContent: string;
49 dependancies = new Map<string, Array<string>>();
50 dependanciesSource = new Map<string, string>();
55 fileToDelete: any = {};
56 parserFactory = new ParserFactory();
59 private packageCreationStore: PackageCreationStore,
60 private templateStore: TemplateStore,
61 private packageCreationUtils: PackageCreationUtils,
62 private toastr: ToastrService,
63 private sharedService: SharedService,
64 private packageCreationService: PackageCreationService,
65 private tourService: TourService,
70 this.templateStore.state$.subscribe(templateInfo => {
71 // init Template&mapping vars
72 console.log('Oninit');
73 console.log(templateInfo);
74 this.templateInfo = templateInfo;
75 this.fileToDelete = templateInfo.fileName;
76 this.fileName = templateInfo.fileName.split('/')[1];
78 this.fileName = this.fileName.split('-')[0];
80 if (templateInfo.type === 'mapping' || templateInfo.type.includes('mapping')) {
81 this.mappingRes = templateInfo.mapping;
82 this.currentMapping = Object.assign({}, templateInfo);
83 this.resourceDictionaryRes = [];
84 this.resTableDtTrigger.next();
87 this.currentMapping = Any;
88 this.resourceDictionaryRes = [];
90 this.templateFileContent = templateInfo.fileContent;
91 this.templateExt = this.templateInfo.ext || this.templateExt ;
92 this.currentTemplate = Object.assign({}, templateInfo);
94 if (templateInfo.type === 'template' || templateInfo.type.includes('template')) {
95 console.log('template extension ' + this.templateExt);
96 this.currentTemplate.fileName = 'Templates/' + this.fileName + '-template.' + this.templateExt;
97 console.log(this.currentTemplate.fileName);
99 this.currentTemplate = Any;
104 this.sharedService.isEdit().subscribe(res => {
105 console.log('------------------------....');
110 console.log('remove ----');
111 this.currentMapping = {};
112 this.currentTemplate = {};
114 this.templateFileContent = '';
115 this.resourceDictionaryRes = [];
116 this.mappingRes = [];
120 this.initDtOptions = {
121 pagingType: 'full_numbers',
127 pagingType: 'full_numbers',
135 switch (this.templateExt) {
147 fileExtensionFromString(filename: string): string {
148 const fileExtension = filename.substring(filename.lastIndexOf('.') + 1);
149 return fileExtension;
152 public getTemplateVariable(fileContent: string) {
153 // TODO: implement factory Pattern for parser
154 console.log('start parsing........ ' + this.templateExt);
155 const parser = this.parserFactory.getParser(fileContent, this.templateExt);
156 return parser.getVariables(fileContent);
159 public dropped(files: NgxFileDropEntry[]) {
161 for (const droppedFile of files) {
162 // Is it a file? & Not added before
163 if (droppedFile.fileEntry.isFile) {
164 const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
165 this.uploadedFiles.push(fileEntry);
166 this.fileNames.add(fileEntry.name);
172 this.uploadedFiles.splice(index, 1);
176 // Delete from templates
177 this.sharedService.deleteFromList(this.fileName);
178 this.packageCreationStore.state.templates.files.delete(this.fileToDelete);
179 // Delete from Mapping
180 this.packageCreationStore.state.mapping.files.delete(this.fileToDelete);
182 this.packageCreationStore.state.templates.files.size > 0 ||
183 this.packageCreationStore.state.mapping.files.size > 0
190 this.dependancies.clear();
191 this.dependanciesSource.clear();
192 if (this.allowedExt.includes('.csv') || this.allowedExt.includes('.xml')) {
193 this.fetchkeysfromfile();
195 this.setTemplateFilesToStore();
197 $('.btn-cancel').click();
200 fetchkeysfromfile() {
201 for (const droppedFile of this.uploadedFiles) {
202 droppedFile.file((file: File) => {
203 const fileReader = new FileReader();
204 fileReader.onload = (e) => {
205 const fileExt = this.fileExtensionFromString(droppedFile.name);
206 if (fileExt === 'csv') {
207 this.variables = fileReader.result.toString().split(',');
209 const parser = new XmlParser();
210 this.variables = parser.getVariables(fileReader.result.toString());
212 console.log(this.variables);
213 this.getMappingTableFromTemplate(null);
216 fileReader.readAsText(file);
219 this.uploadedFiles = [];
222 private convertDictionaryToMap(resourceDictionaries: ResourceDictionary[]): Mapping[] {
223 const mapArray: Mapping[] = [];
224 for (const resourceDictionary of resourceDictionaries) {
225 this.MappingAdapter = new MappingAdapter(resourceDictionary, this.dependancies, this.dependanciesSource);
226 mapArray.push(this.MappingAdapter.ToMapping());
228 console.log(mapArray);
232 setTemplateFilesToStore() {
233 for (const droppedFile of this.uploadedFiles) {
234 droppedFile.file((file: File) => {
235 const fileReader = new FileReader();
236 fileReader.onload = (e) => {
237 this.templateFileContent = fileReader.result.toString();
238 this.variables = this.getTemplateVariable(this.templateFileContent);
239 console.log(this.variables);
242 fileReader.readAsText(file);
245 this.uploadedFiles = [];
248 textChanges(code: any, fileName: string) {
249 // this.packageCreationStore.addTemplate(fileName, code);
250 this.templateFileContent = code;
253 public fileOver(event) {
257 public fileLeave(event) {
261 resetTheUploadedFiles() {
262 this.uploadedFiles = [];
266 console.log('open List view');
267 this.showListView.emit('tell parent to open create views');
271 console.log('close creation view');
272 this.showCreationView.emit('close create form and open list');
275 getMappingTableFromTemplate(e) {
276 console.log('-' + this.templateFileContent + '-');
277 this.resourceDictionaryRes = [];
281 if (this.variables && this.variables.length > 0) {
283 this.packageCreationService.getTemplateAndMapping(this.variables).subscribe(res => {
284 let message = 'Attributes are Fetched';
285 this.mappingRes = [];
286 this.resourceDictionaryRes = res;
287 console.log(this.resourceDictionaryRes);
289 if (this.resourceDictionaryRes && this.resourceDictionaryRes.length <= 0) {
290 message = 'No values for those attributes';
292 this.toastr.success(message, 'Success');
294 this.toastr.error('Error');
300 if (!this.dependanciesSource.has(key)) {
301 this.dependanciesSource.set(key, map.key);
307 this.templateFileContent = '';
308 this.resourceDictionaryRes = [];
309 this.mappingRes = [];
310 this.currentMapping = {};
311 this.currentTemplate = {};
312 // this.closeCreationForm();
316 // check file duplication
317 console.log('----------- mode ' + this.edit);
319 (!(this.packageCreationStore.fileExist('Templates/' + this.fileName + '-mapping.json')
320 || this.packageCreationStore.fileExist('Templates/' + this.fileName + '-template' + this.getFileExtension())))
323 // Save Mapping to Store
324 if (this.resourceDictionaryRes && this.resourceDictionaryRes.length > 0) {
325 const mapArray = this.convertDictionaryToMap(this.resourceDictionaryRes);
326 this.packageCreationStore.addMapping('Templates/' + this.fileName + '-mapping.json',
327 this.packageCreationUtils.transformToJson(this.jsonConvert.serialize(mapArray)));
328 this.resourceDictionaryRes = [];
330 // Save Template to store
331 // if (this.templateFileContent) {
332 this.packageCreationStore.addTemplate('Templates/' + this.fileName + '-template' + this.getFileExtension(),
333 this.templateFileContent);
334 this.templateFileContent = '';
337 this.toastr.success('File is created', 'success');
339 if (localStorage.getItem('tour-guide') !== 'end' && localStorage.getItem('tour-guide') !== 'false') {
340 this.tourService.goto('tm-templateEdit');
343 console.log('this file already exist');
344 this.toastr.error('File name already exist', 'Error');
347 this.toastr.error('Add the file name', 'Error');
352 selectSource(dict, e) {
353 const source = e.target.value;
354 let keyDepend = null;
355 this.dependancies.set(dict.name, null);
357 keyDepend = dict.definition.sources[source].properties['key-dependencies'] || null;
362 this.dependancies.set(dict.name, keyDepend);
364 // this.dependancies.delete(dict.name);
365 // this.dependanciesSource.delete(dict.name);
367 this.dependanciesSource.set(dict.name, source);
368 console.log(this.dependancies);
369 console.log(this.dependanciesSource);
372 getKeys(map: Map<string, any>) {
373 return Array.from(map.keys());
377 return this.dependancies.get(key);
381 this.dtTrigger.next();
384 ngOnDestroy(): void {
385 // Do not forget to unsubscribe the event
386 this.dtTrigger.unsubscribe();
387 this.resTableDtTrigger.unsubscribe();
391 class DependancyVal {
398 this.source = source;
399 this.keyDepend = keyDepend;