import { Injectable } from '@angular/core';
import { CurrencyPipe, DatePipe, DecimalPipe, PercentPipe } from '@angular/common';
import { isNumber } from 'util';
import { of, throwError } from 'rxjs';
import { Observable } from 'rxjs/index';
import _ from 'lodash';
@Injectable({
providedIn: 'root'
})
export class UtilService {
cp: CurrencyPipe = new CurrencyPipe('en-US');
dp: DecimalPipe = new DecimalPipe('en-US');
dtp: DatePipe = new DatePipe('en-US');
pp: PercentPipe = new PercentPipe('en-US');
constructor() { }
buildFlatFileContent(source: any[]): Observable<string> {
let fileContents = '';
try {
if (Array.isArray(source) && source.length) {
fileContents = _.join(source, '\r\n');
}
} catch(e) {
console.error(e);
return throwError(new Error('There was a problem building the flat file contents.'));
}
return of(fileContents);
}
downloadFile(filename: string, contents: string): Observable<any> {
let observable = new Observable(subscriber => {
let blob = new Blob([contents]);
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
subscriber.complete();
} else {
let a = document.createElement('a');
a.style.display = 'none';
document.body.appendChild(a);
a.href = window.URL.createObjectURL(blob);
a.download = filename;
setTimeout(() => {
a.click();
document.body.removeChild(a);
subscriber.next("Success");
subscriber.complete();
}, 500);
}
});
return observable;
}
currencyToNumber(source: string): number {
if (!(typeof source === 'string' && source.length)) {
return NaN;
}
let modifiedSource = source.replace(/[$,]/g, '');
modifiedSource = modifiedSource.replace(/\(/, '-');
modifiedSource = modifiedSource.replace(/\)/, '');
return isNaN(Number(modifiedSource)) ? NaN : parseFloat(modifiedSource);
}
formatFileSize(bytes, decimalPoint) {
if (bytes == 0) return '0 Bytes';
let k = 1000;
let dm = decimalPoint || 2;
let sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
let i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
}