import { Component, Inject, InjectionToken, Injectable, Optional, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { FormsModule } from '@angular/forms';
import { ToastrService, ToastrModule } from 'ngx-toastr';
import { SdButtonModule } from '@sd-angular/core/button';
import { __classPrivateFieldGet } from 'tslib';
import '@sd-angular/core/common';
import { v4 } from 'uuid';
import { SdTranslateService } from '@sd-angular/core/translate';
import { take, takeUntil } from 'rxjs/operators';
import { timer } from 'rxjs';

class DialogConfirmComponent {
    constructor(dialogRef, data) {
        var _a, _b, _c, _d;
        this.dialogRef = dialogRef;
        this.data = data;
        this.required = false;
        this.isString = false;
        this.id = `I${v4()}`;
        this.isString = typeof ((_a = this.data) === null || _a === void 0 ? void 0 : _a.message) === 'string';
        if (data === null || data === void 0 ? void 0 : data.input) {
            this.value = (_c = (_b = data === null || data === void 0 ? void 0 : data.input) === null || _b === void 0 ? void 0 : _b.defaultValue) !== null && _c !== void 0 ? _c : '';
            this.required = ((_d = data === null || data === void 0 ? void 0 : data.input) === null || _d === void 0 ? void 0 : _d.required) || false;
        }
    }
}
DialogConfirmComponent.decorators = [
    { type: Component, args: [{
                selector: 'sd-dialog-confirm',
                template: "<h1 mat-dialog-title class=\"\">\r\n  <mat-icon *ngIf=\"data?.icon\" [ngClass]=\"data?.icon\">\r\n    {{ data?.icon }}\r\n  </mat-icon>\r\n  <span [innerHtml]=\"data?.title || 'Confirm'\"></span>\r\n</h1>\r\n<div mat-dialog-content>\r\n  <div *ngIf=\"isString\" [innerHtml]=\"data?.message\"></div>\r\n  <div *ngIf=\"!isString\" [innerHtml]=\"data?.message | json\"></div>\r\n  <div *ngIf=\"data?.input\">\r\n    <mat-form-field appearance=\"outline\">\r\n      <textarea style=\"width: 100%\" matInput [placeholder]=\"data.input?.placeholder\" [(ngModel)]=\"value\"\r\n        autocomplete=\"off\" rows=\"5\" [maxlength]=\"data.input?.maxlength\"></textarea>\r\n    </mat-form-field>\r\n  </div>\r\n</div>\r\n<div mat-dialog-actions align=\"end\">\r\n  <sd-button *ngIf=\"data?.noTitle\" [color]=\"data?.noButtonColor || 'secondary'\" [mat-dialog-close]=\"'CANCEL'\"\r\n    [title]=\"data?.noTitle\" size=\"sm\"></sd-button>\r\n  <sd-button class=\"ml-12\" *ngIf=\"data?.yesTitle\" [mat-dialog-close]=\"value || 'ACCEPT'\"\r\n    [color]=\"data?.yesButtonColor || 'primary'\" [disabled]=\"required && !value\" cdkFocusInitial\r\n    [title]=\"data?.yesTitle\" size=\"sm\"></sd-button>\r\n</div>",
                styles: [":host .mat-dialog-content{margin:0 -16px 16px!important}:host .mat-button{background-color:#f5f5f5}:host>>>.mat-dialog-title{align-items:center;display:flex;justify-content:flex-start}:host>>>.mat-dialog-title .mat-icon{margin-right:5px}:host{display:block;padding:12px 16px}:host>>>.mat-dialog-title .mat-icon.info{color:#2962ff}:host>>>.mat-dialog-title .mat-icon.warning{color:#ffc107}:host>>>.mat-dialog-title .mat-icon.done{color:#4caf50}:host>>>.mat-dialog-title .mat-icon.error{color:#d32f2f}"]
            },] }
];
DialogConfirmComponent.ctorParameters = () => [
    { type: MatDialogRef },
    { type: undefined, decorators: [{ type: Inject, args: [MAT_DIALOG_DATA,] }] }
];

const NOTIFY_CONFIG = new InjectionToken('notify.configuration');

var _delayDuration, _warningKey, _errorKey, _cache, _notifyWarning, _notifyError, _buildToastMultiMesssage;
class SdNotifyService {
    constructor(dialog, toastr, translateService, configuration) {
        this.dialog = dialog;
        this.toastr = toastr;
        this.translateService = translateService;
        this.configuration = configuration;
        _delayDuration.set(this, 500); // Các error/warning message sẽ tự động gộp sau khoảng thời gian trên
        _warningKey.set(this, v4());
        _errorKey.set(this, v4());
        _cache.set(this, {});
        this.alert = {
            info: (message, title, yesTitle, icon) => {
                this.dialog.open(DialogConfirmComponent, {
                    width: '400px',
                    data: {
                        icon: icon || 'info',
                        title: title || this.translate('Notice'),
                        message: message || 'Done!',
                        yesTitle: yesTitle || this.translate('Ok'),
                    },
                });
            },
            success: (message, title, yesTitle, icon) => {
                this.dialog.open(DialogConfirmComponent, {
                    width: '400px',
                    data: {
                        icon: icon || 'done',
                        title: title || this.translate('Success'),
                        message: message || 'Done!',
                        yesTitle: yesTitle || this.translate('Ok'),
                    },
                });
            },
            warning: (message, title, yesTitle, icon) => {
                this.dialog.open(DialogConfirmComponent, {
                    width: '400px',
                    data: {
                        icon: icon || 'warning',
                        title: title || this.translate('Warning'),
                        message: message || 'Something went wrong!',
                        yesTitle: yesTitle || this.translate('Ok'),
                    },
                });
            },
            error: (message, title, yesTitle, icon) => {
                this.dialog.open(DialogConfirmComponent, {
                    width: '400px',
                    data: {
                        icon: icon || 'error',
                        title: title || this.translate('Error'),
                        message: message || 'Something went wrong!',
                        yesTitle: yesTitle || this.translate('Ok'),
                    },
                });
            },
        };
        this.notify = {
            success: (message, delay, title) => {
                var _a;
                // tslint:disable-next-line: max-line-length
                // const style = `border-radius: 5px; margin: 0; padding: 12px; z-index: 99999; top: 5px; right: 5px; display: none; position: fixed;color: #4F8A10; background-color: #DFF2BF`;
                // tslint:disable-next-line: max-line-length
                // const html = `<div id='${this.notifyId}' style='${style}'><i class='fa fa-check'></i> ${message || this.translate('Success')}</div>`;
                // this.showNotify(html, delay);
                const content = message || this.translate('Success');
                this.toastr.success(content, title, {
                    enableHtml: true,
                    timeOut: delay || ((_a = this.configuration) === null || _a === void 0 ? void 0 : _a.timeDelay) || 3000,
                    closeButton: true,
                });
            },
            warning: (message, delay, title) => {
                if (!__classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _warningKey)] || Date.addMiliseconds(__classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _warningKey)].createdDate, __classPrivateFieldGet(this, _delayDuration)) < new Date()) {
                    __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _warningKey)] = {
                        createdDate: new Date(),
                        data: {
                            title: title,
                            messages: [],
                        }
                    };
                    timer(__classPrivateFieldGet(this, _delayDuration)).pipe(take(1)).subscribe(() => {
                        const messages = __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _warningKey)].data.messages.union(null);
                        if (messages.length === 1) {
                            __classPrivateFieldGet(this, _notifyWarning).call(this, {
                                title: __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _warningKey)].data.title,
                                message: messages[0],
                                delay
                            });
                        }
                        else {
                            __classPrivateFieldGet(this, _notifyWarning).call(this, {
                                title: __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _warningKey)].data.title,
                                message: messages,
                                delay
                            });
                        }
                    });
                }
                if (Array.isArray(message)) {
                    __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _warningKey)].data.messages = [...__classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _warningKey)].data.messages, ...message];
                }
                else {
                    __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _warningKey)].data.messages.push(message);
                }
            },
            error: (message, delay, title) => {
                if (!__classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _errorKey)] || Date.addMiliseconds(__classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _errorKey)].createdDate, __classPrivateFieldGet(this, _delayDuration)) < new Date()) {
                    __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _errorKey)] = {
                        createdDate: new Date(),
                        data: {
                            title,
                            messages: [],
                        }
                    };
                    timer(__classPrivateFieldGet(this, _delayDuration)).pipe(take(1)).subscribe(() => {
                        const messages = __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _errorKey)].data.messages.union(null);
                        if (messages.length === 1) {
                            __classPrivateFieldGet(this, _notifyError).call(this, {
                                title: __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _errorKey)].data.title,
                                message: messages[0],
                                delay
                            });
                        }
                        else {
                            __classPrivateFieldGet(this, _notifyError).call(this, {
                                title: __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _errorKey)].data.title,
                                message: messages,
                                delay
                            });
                        }
                    });
                }
                if (Array.isArray(message)) {
                    __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _errorKey)].data.messages = [...__classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _errorKey)].data.messages, ...message];
                }
                else {
                    __classPrivateFieldGet(this, _cache)[__classPrivateFieldGet(this, _errorKey)].data.messages.push(message);
                }
            },
        };
        _notifyWarning.set(this, (args) => {
            var _a;
            const { message, delay, title } = args;
            if (Array.isArray(message)) {
                __classPrivateFieldGet(this, _buildToastMultiMesssage).call(this, 'warning', message, delay, title);
            }
            else {
                const content = message || this.translate('Warning');
                this.toastr.warning(content, title, {
                    enableHtml: true,
                    timeOut: delay || ((_a = this.configuration) === null || _a === void 0 ? void 0 : _a.timeDelay) || 3000,
                    closeButton: true,
                });
            }
        });
        _notifyError.set(this, (args) => {
            var _a;
            const { message, delay, title } = args;
            if (Array.isArray(message)) {
                __classPrivateFieldGet(this, _buildToastMultiMesssage).call(this, 'error', message, delay, title);
            }
            else {
                const content = message || this.translate('Error');
                this.toastr.error(content, title, {
                    enableHtml: true,
                    timeOut: delay || ((_a = this.configuration) === null || _a === void 0 ? void 0 : _a.timeDelay) || 3000,
                    closeButton: true,
                });
            }
        });
        _buildToastMultiMesssage.set(this, (type, messages, delay, title) => {
            var _a, _b;
            /** số lượng item hiển thị mặc định */
            const showNum = 2;
            const id = `sd-notify-ckb-${v4()}`;
            const messageLength = messages.length;
            const messageRests = messages.splice(showNum);
            const messageContainer = `<ul class='sd-notify__list'>{0}{1}</ul>`;
            const messageTemp = `<li class='sd-notify__item'>- {0}</li>`;
            let contentRest = '';
            if (messageRests === null || messageRests === void 0 ? void 0 : messageRests.length) {
                contentRest = `<input id='${id}' class='cdk-visually-hidden sd-notify__checkbox' type='checkbox' />
      <label class='sd-notify__text sd-notify__text--show' for='${id}'>${this.translate('Show more')}</label>
      <div class='sd-notify__item--rest'>
        ${messageRests.map(m => String.format(messageTemp, m)).join('')}
      </div>
      <label class='sd-notify__text sd-notify__text--less' for='${id}'>${this.translate('Show less')}</label>`;
            }
            const content = String.format(messageContainer, messages.map(m => String.format(messageTemp, m)).join(''), contentRest);
            let toast;
            // khi truyền message html sẽ bị sanitize nên phải truyền innerHTML khi toast hiện lên
            // @see https://github.com/scttcper/ngx-toastr/blob/v12.1.0/src/lib/toastr/toastr.service.ts#L271
            switch (type) {
                case 'error':
                    toast = this.toastr.error(content, `${title || this.translate('Error')} (${messageLength})`, {
                        enableHtml: true,
                        timeOut: delay || ((_a = this.configuration) === null || _a === void 0 ? void 0 : _a.timeDelay) || 3000,
                        messageClass: `toast-message toast-message-${id}`,
                        closeButton: true,
                        tapToDismiss: false
                    });
                    break;
                case 'warning':
                    toast = this.toastr.warning(content, `${title || this.translate('Warning')} (${messageLength})`, {
                        enableHtml: true,
                        timeOut: delay || ((_b = this.configuration) === null || _b === void 0 ? void 0 : _b.timeDelay) || 3000,
                        messageClass: `toast-message toast-message-${id}`,
                        closeButton: true,
                        tapToDismiss: false
                    });
                    break;
            }
            if (toast) {
                toast.onShown
                    .pipe(takeUntil(toast.onHidden))
                    .subscribe(() => {
                    const messageEle = document.querySelector(`.toast-message-${id}`);
                    messageEle.innerHTML = content;
                });
            }
        });
        this.handle = {
            error: (err) => {
                if (typeof err === 'string') {
                    this.notify.warning(err);
                }
                else if (typeof err === 'object') {
                    let message = (err === null || err === void 0 ? void 0 : err.error) || (err === null || err === void 0 ? void 0 : err.message) || (err === null || err === void 0 ? void 0 : err.ExceptionMessage) || (err === null || err === void 0 ? void 0 : err.Message) ||
                        'Unknown error';
                    if (typeof err.json === 'function') {
                        err = err.json();
                        if (err) {
                            message =
                                (err === null || err === void 0 ? void 0 : err.error) || (err === null || err === void 0 ? void 0 : err.message) || (err === null || err === void 0 ? void 0 : err.ExceptionMessage) || (err === null || err === void 0 ? void 0 : err.Message) ||
                                    'Unknown error';
                        }
                    }
                    this.notify.warning(message);
                }
                else {
                    this.notify.warning('Unknown error');
                }
            },
        };
        this.confirm = (message, option = {}) => {
            const dialogRef = this.dialog.open(DialogConfirmComponent, {
                width: '400px',
                data: {
                    title: (option === null || option === void 0 ? void 0 : option.title) || this.translate('Confirm'),
                    message,
                    yesTitle: (option === null || option === void 0 ? void 0 : option.yesTitle) || this.translate('Yes'),
                    noTitle: (option === null || option === void 0 ? void 0 : option.noTitle) || this.translate('No'),
                    noButtonColor: (option === null || option === void 0 ? void 0 : option.noButtonColor) || 'secondary',
                    yesButtonColor: (option === null || option === void 0 ? void 0 : option.yesButtonColor) || 'primary',
                },
            });
            return new Promise((resolve, reject) => {
                dialogRef.afterClosed().subscribe((result) => {
                    if (result) {
                        if (result === 'ACCEPT') {
                            resolve(null);
                        }
                        else if (result === 'CANCEL') {
                            reject(result);
                        }
                        else {
                            resolve(null);
                        }
                    }
                });
            });
        };
        this.confirmDelete = () => this.confirm(this.translate('Delete record(s)'));
        this.confirmApprove = () => this.confirm(this.translate('Approve record(s)'));
        this.confirmWithInput = (title, option = {}) => {
            const dialogRef = this.dialog.open(DialogConfirmComponent, {
                width: '400px',
                data: {
                    title: title || this.translate('Confirm'),
                    message: option === null || option === void 0 ? void 0 : option.message,
                    yesTitle: (option === null || option === void 0 ? void 0 : option.yesTitle) || this.translate('Yes'),
                    noTitle: (option === null || option === void 0 ? void 0 : option.noTitle) || this.translate('No'),
                    noButtonColor: (option === null || option === void 0 ? void 0 : option.noButtonColor) || 'secondary',
                    yesButtonColor: (option === null || option === void 0 ? void 0 : option.yesButtonColor) || 'primary',
                    input: {
                        maxlength: (option === null || option === void 0 ? void 0 : option.maxlength) || 255,
                        required: option === null || option === void 0 ? void 0 : option.required,
                        defaultValue: (option === null || option === void 0 ? void 0 : option.defaultValue) || ''
                    },
                },
            });
            return new Promise((resolve, reject) => {
                dialogRef.afterClosed().subscribe((result) => {
                    if (result) {
                        if (result === 'ACCEPT') {
                            resolve(result);
                        }
                        else if (result === 'CANCEL') {
                            reject(result);
                        }
                        else {
                            resolve(result);
                        }
                    }
                });
            });
        };
        this.translate = (value) => {
            return this.translateService.translate(value);
        };
    }
}
_delayDuration = new WeakMap(), _warningKey = new WeakMap(), _errorKey = new WeakMap(), _cache = new WeakMap(), _notifyWarning = new WeakMap(), _notifyError = new WeakMap(), _buildToastMultiMesssage = new WeakMap();
SdNotifyService.decorators = [
    { type: Injectable }
];
SdNotifyService.ctorParameters = () => [
    { type: MatDialog },
    { type: ToastrService },
    { type: SdTranslateService },
    { type: undefined, decorators: [{ type: Inject, args: [NOTIFY_CONFIG,] }, { type: Optional }] }
];

class SdNotifyModule {
}
SdNotifyModule.decorators = [
    { type: NgModule, args: [{
                imports: [
                    CommonModule,
                    FormsModule,
                    MatFormFieldModule,
                    MatInputModule,
                    MatIconModule,
                    MatButtonModule,
                    MatDialogModule,
                    ToastrModule.forRoot(),
                    SdButtonModule,
                ],
                declarations: [DialogConfirmComponent],
                entryComponents: [DialogConfirmComponent],
                exports: [],
                providers: [SdNotifyService],
            },] }
];

/*
 * Public API Surface of superdev-angular-core
 */

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

export { DialogConfirmComponent, NOTIFY_CONFIG, SdNotifyModule, SdNotifyService };
//# sourceMappingURL=sd-angular-core-notify.js.map
