import '@sd-angular/core/common';
import { Directive, TemplateRef, ViewContainerRef, Pipe, ɵɵdefineInjectable, Injectable, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DeviceDetectorService } from 'ngx-device-detector';
import { DomSanitizer } from '@angular/platform-browser';
import { of, interval } from 'rxjs';
import { map } from 'rxjs/operators';
import { __classPrivateFieldGet, __awaiter } from 'tslib';
import md5 from 'md5';
import { v4 } from 'uuid';

class SdDesktopDirective {
    constructor(templateRef, viewContainerRef, deviceService) {
        this.templateRef = templateRef;
        this.viewContainerRef = viewContainerRef;
        if (deviceService.isDesktop()) {
            this.viewContainerRef.createEmbeddedView(this.templateRef);
        }
    }
}
SdDesktopDirective.decorators = [
    { type: Directive, args: [{
                selector: '[sdDesktop]'
            },] }
];
SdDesktopDirective.ctorParameters = () => [
    { type: TemplateRef },
    { type: ViewContainerRef },
    { type: DeviceDetectorService }
];

class SdMobileDirective {
    constructor(templateRef, viewContainerRef, deviceService) {
        this.templateRef = templateRef;
        this.viewContainerRef = viewContainerRef;
        if (deviceService.isMobile()) {
            this.viewContainerRef.createEmbeddedView(this.templateRef);
        }
    }
}
SdMobileDirective.decorators = [
    { type: Directive, args: [{
                selector: '[sdMobile]'
            },] }
];
SdMobileDirective.ctorParameters = () => [
    { type: TemplateRef },
    { type: ViewContainerRef },
    { type: DeviceDetectorService }
];

class SdMobileTabletDirective {
    constructor(templateRef, viewContainerRef, deviceService) {
        this.templateRef = templateRef;
        this.viewContainerRef = viewContainerRef;
        if (deviceService.isMobile() || deviceService.isTablet()) {
            this.viewContainerRef.createEmbeddedView(this.templateRef);
        }
    }
}
SdMobileTabletDirective.decorators = [
    { type: Directive, args: [{
                selector: '[sdMobileTablet]'
            },] }
];
SdMobileTabletDirective.ctorParameters = () => [
    { type: TemplateRef },
    { type: ViewContainerRef },
    { type: DeviceDetectorService }
];

class SdTabletDirective {
    constructor(templateRef, viewContainerRef, deviceService) {
        this.templateRef = templateRef;
        this.viewContainerRef = viewContainerRef;
        if (deviceService.isTablet()) {
            this.viewContainerRef.createEmbeddedView(this.templateRef);
        }
    }
}
SdTabletDirective.decorators = [
    { type: Directive, args: [{
                selector: '[sdTablet]'
            },] }
];
SdTabletDirective.ctorParameters = () => [
    { type: TemplateRef },
    { type: ViewContainerRef },
    { type: DeviceDetectorService }
];

class SdCurrencyPipe {
    transform(value, digits) {
        return Number.toVNCurrency(value, digits);
    }
}
SdCurrencyPipe.decorators = [
    { type: Pipe, args: [{
                name: 'sdCurrency',
            },] }
];

class SdSafeHtmlPipe {
    constructor(sanitizer) {
        this.sanitizer = sanitizer;
    }
    transform(html) {
        return this.sanitizer.bypassSecurityTrustHtml(html);
    }
}
SdSafeHtmlPipe.decorators = [
    { type: Pipe, args: [{
                name: 'safeHtml',
            },] }
];
SdSafeHtmlPipe.ctorParameters = () => [
    { type: DomSanitizer }
];

var _translate;
class SdUtilityService {
    constructor() {
        _translate.set(this, (value) => value);
        this.hashMD5 = (key) => md5(key);
        this.arrayToObject = (items, key) => {
            return items.reduce((obj, item) => { obj[item[key]] = item; return obj; }, {});
        };
        this.changeAliasLowerCase = (alias) => {
            var _a;
            let str = (_a = alias === null || alias === void 0 ? void 0 : alias.toString()) !== null && _a !== void 0 ? _a : '';
            str = str.toString().toLowerCase();
            str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, 'a');
            str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, 'e');
            str = str.replace(/ì|í|ị|ỉ|ĩ/g, 'i');
            str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, 'o');
            str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, 'u');
            str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, 'y');
            str = str.replace(/đ/g, 'd');
            str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'|\"|\&|\#|\[|\]|~|\$|_|`|-|{|}|\||\\/g, ' ');
            str = str.replace(/ + /g, ' ');
            str = str.trim();
            return str;
        };
        this.timeDifference = (previous, current = new Date()) => {
            if (!Date.isDate(previous)) {
                return '';
            }
            if (!Date.isDate(current)) {
                return '';
            }
            const from = new Date(previous);
            const to = new Date(current);
            const msPerMinute = 60 * 1000;
            const msPerHour = msPerMinute * 60;
            const msPerDay = msPerHour * 24;
            const msPerMonth = msPerDay * 30;
            const msPerYear = msPerDay * 365;
            const elapsed = to.getTime() - from.getTime();
            if (elapsed < msPerMinute) {
                return `${Math.round(elapsed / 1000)} ${__classPrivateFieldGet(this, _translate).call(this, 'seconds ago')}`;
            }
            if (elapsed < msPerHour) {
                return `${Math.round(elapsed / msPerMinute)} ${__classPrivateFieldGet(this, _translate).call(this, 'minutes ago')}`;
            }
            if (elapsed < msPerDay) {
                return `${Math.round(elapsed / msPerHour)} ${__classPrivateFieldGet(this, _translate).call(this, 'hours ago')}`;
            }
            if (elapsed < msPerMonth) {
                return `${Math.round(elapsed / msPerDay)} ${__classPrivateFieldGet(this, _translate).call(this, 'days ago')}`;
            }
            if (elapsed < msPerYear) {
                return `${Math.round(elapsed / msPerMonth)} ${__classPrivateFieldGet(this, _translate).call(this, 'months ago')}`;
            }
            return `${Math.round(elapsed / msPerYear)} ${__classPrivateFieldGet(this, _translate).call(this, 'years ago')}`;
        };
        this.upload = (option) => {
            return SdUtility.upload(option);
        };
        this.download = (filePath, fileName) => {
            const link = document.createElement('a');
            link.download = `${fileName || v4()}`;
            link.href = filePath;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        };
        this.copyToClipboard = (text) => {
            navigator.clipboard.writeText(text);
        };
        this.printHtml = (elementId, fileName) => {
            const printId = `sdPrintSection`;
            const div = 'sd-print';
            const elem = document.getElementById(elementId).firstElementChild;
            const domClone = elem.cloneNode(true);
            const printSection = document.createElement('div');
            printSection.id = printId;
            printSection.appendChild(domClone);
            document.body.insertBefore(printSection, document.body.firstChild);
            document.querySelector('body app-root').classList.add(div);
            const title = document.title;
            if (fileName) {
                document.title = fileName;
            }
            window.print();
            document.title = title;
            document.querySelector('body app-root').classList.remove(div);
            const oldElem = document.getElementById(printId);
            if (oldElem !== null) {
                oldElem.parentNode.removeChild(oldElem); // oldElem.remove() not supported by IE
            }
        };
        this.allWithPaging = (func, defaultPageSize) => __awaiter(this, void 0, void 0, function* () {
            var _a;
            let pageSize = defaultPageSize || 1000;
            let pageNumber = 0;
            let count = 0;
            let items = [];
            while (true) {
                const res = yield func(pageSize, pageNumber);
                if (Array(res === null || res === void 0 ? void 0 : res.items) && (res === null || res === void 0 ? void 0 : res.total) > 0) {
                    items = [...items, ...res.items];
                    count += res.items.length;
                    pageNumber++;
                    if (count >= res.total || !((_a = res.items) === null || _a === void 0 ? void 0 : _a.length)) {
                        return items;
                    }
                }
                else {
                    return [];
                }
            }
        });
    }
}
_translate = new WeakMap();
SdUtilityService.ɵprov = ɵɵdefineInjectable({ factory: function SdUtilityService_Factory() { return new SdUtilityService(); }, token: SdUtilityService, providedIn: "root" });
SdUtilityService.decorators = [
    { type: Injectable, args: [{
                providedIn: 'root'
            },] }
];
SdUtilityService.ctorParameters = () => [];

class SdTimeDifferentPipe {
    constructor(utilityService) {
        this.utilityService = utilityService;
        this.maxSecond = 60;
        this.maxMinute = this.maxSecond * 60;
        this.maxHour = this.maxMinute * 24;
        this.maxDay = this.maxHour * 30;
        this.maxMonth = this.maxHour * 365;
    }
    transform(value, format, different) {
        if (!Date.isDate(value)) {
            return of(null);
        }
        if (!different) {
            return of(Date.toFormat(value, format));
        }
        if (Math.round((new Date().getTime() - new Date(value).getTime()) / 1000) < 0) {
            return of(Date.toFormat(value, format));
        }
        return interval(1000).pipe(map(() => {
            const timeDifferent = Math.round((new Date().getTime() - new Date(value).getTime()) / 1000);
            if (different === 'month' && timeDifferent < this.maxMonth) {
                return this.utilityService.timeDifference(value);
            }
            if (different === 'day' && timeDifferent < this.maxDay) {
                return this.utilityService.timeDifference(value);
            }
            if (different === 'hour' && timeDifferent < this.maxHour) {
                return this.utilityService.timeDifference(value);
            }
            if (different === 'minute' && timeDifferent < this.maxMinute) {
                return this.utilityService.timeDifference(value);
            }
            if (different === 'second' && timeDifferent < this.maxSecond) {
                return this.utilityService.timeDifference(value);
            }
            return Date.toFormat(value, format);
        }));
    }
}
SdTimeDifferentPipe.decorators = [
    { type: Pipe, args: [{
                name: 'sdTimeDifferent',
            },] }
];
SdTimeDifferentPipe.ctorParameters = () => [
    { type: SdUtilityService }
];

class SdUtilityModule {
}
SdUtilityModule.decorators = [
    { type: NgModule, args: [{
                imports: [
                    CommonModule,
                ],
                declarations: [
                    SdDesktopDirective,
                    SdMobileTabletDirective,
                    SdMobileDirective,
                    SdTabletDirective,
                    SdCurrencyPipe,
                    SdSafeHtmlPipe,
                    SdTimeDifferentPipe
                ],
                exports: [
                    SdDesktopDirective,
                    SdMobileTabletDirective,
                    SdMobileDirective,
                    SdTabletDirective,
                    SdCurrencyPipe,
                    SdSafeHtmlPipe,
                    SdTimeDifferentPipe
                ],
                providers: [
                    SdCurrencyPipe,
                    SdSafeHtmlPipe,
                    SdTimeDifferentPipe
                ]
            },] }
];

/**
 * Generated bundle index. Do not edit.
 */

export { SdCurrencyPipe, SdDesktopDirective, SdMobileDirective, SdMobileTabletDirective, SdSafeHtmlPipe, SdTabletDirective, SdTimeDifferentPipe, SdUtilityModule, SdUtilityService };
//# sourceMappingURL=sd-angular-core-utility.js.map
