import-vessels.component.ts
2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {VesselsService} from '../../service/vessels.service';
import {Message} from '../../model/message';
import {Vessel} from '../../model/vessel';
import {Vessels} from '../../model/vessels';
@Component({
selector: 'app-import-vessels',
templateUrl: './import-vessels.component.html',
styleUrls: ['./import-vessels.component.scss']
})
export class ImportVesselsComponent implements OnInit {
vessels: Vessels;
constructor(private vesselsService: VesselsService) {
}
@ViewChild('fileDropRef', {static: false}) fileDropEl: ElementRef;
files: any[] = [];
ngOnInit(): void {
this.vesselsService.currentVessels.subscribe(vessels => this.vessels = vessels);
}
/**
* on file drop handler
*/
onFileDropped($event): void {
this.prepareFilesList($event);
}
/**
* handle file from browsing
*/
fileBrowseHandler(files): void {
this.prepareFilesList(files);
}
/**
* Delete file from files list
* @param index (File index)
*/
deleteFile(index: number): void {
if (this.files[index].progress < 100) {
return;
}
this.files.splice(index, 1);
}
uploadFilesSimulator(index: number): void {
const fileReader = new FileReader();
let nbLine: number;
fileReader.onload = (e) => {
this.vessels = new Vessels();
const lines: string[] = (fileReader.result as string).split('\n');
nbLine = lines.length;
for (let line of lines) {
line = line.replace(/[^\x20-\x7F]/g, '');
const splitLine = line.split(',');
if (isNaN(Number(splitLine[0])) || line === '') {
continue;
}
const newMessage = new Message(splitLine);
this.vessels.addMessage(newMessage);
}
this.vesselsService.changeVesselsSet(this.vessels);
};
fileReader.onprogress = (e ) => {
if (e.lengthComputable) {
this.files[index].progress = Math.round(((e.loaded / e.total) * 100));
}
};
fileReader.readAsText(this.files[index]);
}
prepareFilesList(files: Array<any>): void {
for (const item of files) {
item.progress = 0;
this.files.push(item);
}
this.fileDropEl.nativeElement.value = '';
this.uploadFilesSimulator(0);
}
formatBytes(bytes, decimals = 2): string {
if (bytes === 0) {
return '0 Bytes';
}
const k = 1024;
const dm = decimals <= 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
}