import { EventEmitter, Component, ChangeDetectionStrategy, ChangeDetectorRef, Inject, Optional, Input, Output, ContentChild, ViewChild, Pipe, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { __classPrivateFieldGet, __awaiter, __classPrivateFieldSet } from 'tslib';
import { Validators, NgForm, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { v4 } from 'uuid';
import { Subscription } from 'rxjs';
import { CurrencyMaskInputMode, NgxCurrencyModule } from 'ngx-currency';
import { SdFormControl, FORM_CONFIG, SdSuffixDirective, SdLabelDefDirective, SdCommonModule } from '@sd-angular/core/common';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { SdTranslateModule } from '@sd-angular/core/translate';

var _name, _form, _model, _align, _allowNegative, _decimal, _precision, _prefix, _suffix, _thousands, _nullable, _min, _max, _pattern, _validator, _subscription, _generateOption, _updateValidator, _onChange, _customValidator;
class SdInputCurrency {
    constructor(ref, formConfig) {
        this.ref = ref;
        this.formConfig = formConfig;
        _name.set(this, v4());
        this.disableErrorMessage = false;
        _form.set(this, void 0);
        _model.set(this, void 0);
        this.modelChange = new EventEmitter();
        _align.set(this, 'left');
        _allowNegative.set(this, true);
        _decimal.set(this, ',');
        _precision.set(this, 0);
        _prefix.set(this, void 0);
        _suffix.set(this, void 0);
        _thousands.set(this, '.');
        _nullable.set(this, void 0);
        _min.set(this, void 0);
        _max.set(this, void 0);
        // Validator
        this.isRequired = false;
        _pattern.set(this, void 0);
        _validator.set(this, void 0);
        this.sdChange = new EventEmitter();
        this.sdFocus = new EventEmitter();
        this.keyupEnter = new EventEmitter();
        this.formControl = new SdFormControl();
        _subscription.set(this, new Subscription());
        this.options = {};
        _generateOption.set(this, () => {
            this.options = {
                align: __classPrivateFieldGet(this, _align) || '',
                allowNegative: __classPrivateFieldGet(this, _allowNegative),
                decimal: __classPrivateFieldGet(this, _decimal),
                precision: __classPrivateFieldGet(this, _precision),
                prefix: __classPrivateFieldGet(this, _prefix) || '',
                suffix: __classPrivateFieldGet(this, _suffix) || '',
                thousands: __classPrivateFieldGet(this, _thousands),
                nullable: __classPrivateFieldGet(this, _nullable),
                min: __classPrivateFieldGet(this, _min),
                max: __classPrivateFieldGet(this, _max),
                inputMode: CurrencyMaskInputMode.NATURAL
            };
            this.ref.markForCheck();
        });
        this.reValidate = () => {
            this.formControl.updateValueAndValidity();
        };
        _updateValidator.set(this, () => {
            this.formControl.clearValidators();
            this.formControl.clearAsyncValidators();
            const validators = [];
            const asyncValidators = [];
            if (this.isRequired) {
                validators.push(Validators.required);
            }
            if (__classPrivateFieldGet(this, _pattern)) {
                validators.push(Validators.pattern(__classPrivateFieldGet(this, _pattern)));
            }
            if (__classPrivateFieldGet(this, _validator)) {
                asyncValidators.push(__classPrivateFieldGet(this, _customValidator).call(this, __classPrivateFieldGet(this, _validator)));
            }
            if (this.inlineError) {
                validators.push(this.customInlineErrorValidator());
            }
            this.formControl.setValidators(validators);
            this.formControl.setAsyncValidators(asyncValidators);
            this.formControl.updateValueAndValidity();
        }
        // Hàm tạo Validators tùy chỉnh cho inlineError
        );
        _onChange.set(this, (value) => __awaiter(this, void 0, void 0, function* () {
            this.modelChange.emit(value);
            this.sdChange.emit(value);
        }));
        this.onKeyupEnter = () => {
            this.keyupEnter.emit(this.formControl.value);
        };
        this.onFocus = () => {
            this.sdFocus.emit();
        };
        this.onBlur = () => {
            var _a;
            const val = ((_a = this.formControl.value) !== null && _a !== void 0 ? _a : '').toString();
            if (val.length > val.trim().length) {
                this.formControl.setValue(val.trim());
            }
            this.ref.markForCheck();
        };
        _customValidator.set(this, (func) => {
            return (c) => __awaiter(this, void 0, void 0, function* () {
                const value = c.value || null;
                if (func && typeof (func) === 'function') {
                    const result = func(value);
                    if (result instanceof Promise) {
                        const message = yield result;
                        if (message) {
                            return {
                                customValidator: message
                            };
                        }
                        return null;
                    }
                    if (result) {
                        return {
                            customValidator: result
                        };
                    }
                    return null;
                }
                return null;
            });
        });
    }
    set name(val) {
        if (val) {
            __classPrivateFieldSet(this, _name, val);
        }
    }
    set _disableErrorMessage(val) {
        this.disableErrorMessage = (val === '') || val;
        val = (val === '') || val;
    }
    set form(val) {
        if (val) {
            if (val instanceof NgForm) {
                __classPrivateFieldSet(this, _form, val.form);
            }
            else {
                __classPrivateFieldSet(this, _form, val);
            }
        }
    }
    set model(value) {
        if (__classPrivateFieldGet(this, _model) !== value) {
            __classPrivateFieldSet(this, _model, value);
            this.formControl.setValue(value, {
                emitEvent: false
            });
        }
    }
    set align(val) {
        __classPrivateFieldSet(this, _align, val || 'left');
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set allowNegative(val) {
        __classPrivateFieldSet(this, _allowNegative, (val === '') || val);
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set decimal(val) {
        __classPrivateFieldSet(this, _decimal, val || ',');
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set precision(val) {
        __classPrivateFieldSet(this, _precision, val || 0);
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set prefix(val) {
        __classPrivateFieldSet(this, _prefix, val);
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set suffix(val) {
        __classPrivateFieldSet(this, _suffix, val);
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set thousands(val) {
        __classPrivateFieldSet(this, _thousands, val || '.');
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set nullable(val) {
        __classPrivateFieldSet(this, _nullable, val);
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set min(val) {
        __classPrivateFieldSet(this, _min, val);
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set max(val) {
        __classPrivateFieldSet(this, _max, val);
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    set required(val) {
        this.isRequired = (val === '') || val;
        __classPrivateFieldGet(this, _updateValidator).call(this);
    }
    set pattern(val) {
        __classPrivateFieldSet(this, _pattern, val);
        __classPrivateFieldGet(this, _updateValidator).call(this);
    }
    set validator(validator) {
        __classPrivateFieldSet(this, _validator, validator);
        __classPrivateFieldGet(this, _updateValidator).call(this);
    }
    set _inlineError(val) {
        this.inlineError = val;
        __classPrivateFieldGet(this, _updateValidator).call(this);
    }
    // Optional
    set disabled(val) {
        val = (val === '') || val;
        if (val) {
            this.formControl.disable();
        }
        else {
            this.formControl.enable();
        }
    }
    ngOnInit() {
        var _a;
        this.appearance = this.appearance || ((_a = this.formConfig) === null || _a === void 0 ? void 0 : _a.appearance);
        __classPrivateFieldGet(this, _subscription).add(this.formControl.sdChanges.subscribe(() => {
            this.ref.markForCheck();
        }));
        __classPrivateFieldGet(this, _generateOption).call(this);
    }
    ngAfterViewInit() {
        var _a;
        __classPrivateFieldGet(this, _subscription).add(this.formControl.valueChanges.subscribe(__classPrivateFieldGet(this, _onChange)));
        (_a = __classPrivateFieldGet(this, _form)) === null || _a === void 0 ? void 0 : _a.addControl(__classPrivateFieldGet(this, _name), this.formControl);
        this.ref.detectChanges();
    }
    ngOnDestroy() {
        var _a;
        (_a = __classPrivateFieldGet(this, _form)) === null || _a === void 0 ? void 0 : _a.removeControl(__classPrivateFieldGet(this, _name));
        __classPrivateFieldGet(this, _subscription).unsubscribe();
    }
    // Hàm tạo Validators tùy chỉnh cho inlineError
    customInlineErrorValidator() {
        return (control) => {
            return { inlineError: true };
        };
    }
}
_name = new WeakMap(), _form = new WeakMap(), _model = new WeakMap(), _align = new WeakMap(), _allowNegative = new WeakMap(), _decimal = new WeakMap(), _precision = new WeakMap(), _prefix = new WeakMap(), _suffix = new WeakMap(), _thousands = new WeakMap(), _nullable = new WeakMap(), _min = new WeakMap(), _max = new WeakMap(), _pattern = new WeakMap(), _validator = new WeakMap(), _subscription = new WeakMap(), _generateOption = new WeakMap(), _updateValidator = new WeakMap(), _onChange = new WeakMap(), _customValidator = new WeakMap();
SdInputCurrency.decorators = [
    { type: Component, args: [{
                selector: 'sd-input-currency',
                template: "<ng-container *ngIf=\"!appearance && sdLabelDef?.templateRef\">\r\n  <ng-container *ngTemplateOutlet=\"sdLabelDef.templateRef\">\r\n  </ng-container>\r\n</ng-container>\r\n<label *ngIf=\"!appearance && label && !sdLabelDef?.templateRef\" class=\"d-block mb-0 T14M\">{{label}} <span class=\"text-danger mb-2\" *ngIf=\"isRequired\">*</span></label>\r\n<div class=\"d-flex align-items-center\">\r\n  <mat-form-field class=\"sd-md\"\r\n    [ngClass]=\"{'sd-form-tooltip':tooltip, 'sd-sm': size === 'sm', 'no-padding-wrapper': disableErrorMessage}\"\r\n    [appearance]=\"appearance || 'outline'\">\r\n    <mat-label *ngIf=\"appearance && label\">{{label}}</mat-label>\r\n    <input currencyMask [options]=\"options\" [formControl]=\"formControl\" #control matInput\r\n      [placeholder]=\"placeholder || (appearance ? label : '')\" (keyup.enter)=\"onKeyupEnter()\" (focus)=\"onFocus()\" [required]=\"isRequired\"\r\n      autocomplete=\"off\">\r\n    <ng-container *ngIf=\"sdSuffix?.templateRef\" matSuffix>\r\n      <ng-container *ngTemplateOutlet=\"sdSuffix.templateRef\">\r\n      </ng-container>\r\n    </ng-container>\r\n    <mat-error *ngIf=\"formControl.errors?.required && !disableErrorMessage\">\r\n      {{'This field is required' | sdTranslate}}\r\n    </mat-error>\r\n    <mat-error *ngIf=\"formControl.errors?.pattern && !disableErrorMessage\">\r\n      {{'Pattern error' | sdTranslate}}\r\n    </mat-error>\r\n    <mat-error *ngIf=\"formControl.errors?.customValidator && !disableErrorMessage\">\r\n      <strong>{{formControl.errors?.customValidator}}</strong>\r\n    </mat-error>\r\n    <mat-error *ngIf=\"formControl.errors?.inlineError\">\r\n      <ng-container *ngIf=\"!disableErrorMessage\">{{inlineError}}</ng-container>\r\n    </mat-error>\r\n  </mat-form-field>\r\n  <div *ngIf=\"tooltip\" class=\"sd-tooltip\">\r\n    <mat-icon (click)=\"sdTooltip.toggle()\" [matTooltip]=\"formControl.value | sdInputCurrencyTooltipPipe:tooltip\"\r\n      matSuffix #sdTooltip=\"matTooltip\">info</mat-icon>\r\n  </div>\r\n</div>",
                changeDetection: ChangeDetectionStrategy.OnPush,
                styles: [":host ::ng-deep .mat-form-field.sd-form-tooltip{width:calc(100% - 30px)}.sd-tooltip{display:inline-block;margin:auto;text-align:center;width:30px}:host{display:block;padding-top:5px}:host ::ng-deep .mat-form-field.no-padding-wrapper .mat-form-field-wrapper{padding-bottom:0}:host ::ng-deep .mat-form-field.mat-form-field-appearance-outline.mat-form-field-disabled .mat-form-field-outline{background:#f6f6f6;color:#e9e9e9}:host ::ng-deep .mat-form-field input.mat-input-element:disabled{color:#4d4d4d!important}:host ::ng-deep .mat-form-field .mat-placeholder-required{color:#f82c13}"]
            },] }
];
SdInputCurrency.ctorParameters = () => [
    { type: ChangeDetectorRef },
    { type: undefined, decorators: [{ type: Inject, args: [FORM_CONFIG,] }, { type: Optional }] }
];
SdInputCurrency.propDecorators = {
    name: [{ type: Input }],
    appearance: [{ type: Input }],
    _disableErrorMessage: [{ type: Input, args: ['disableErrorMessage',] }],
    size: [{ type: Input }],
    form: [{ type: Input }],
    label: [{ type: Input }],
    placeholder: [{ type: Input }],
    model: [{ type: Input }],
    modelChange: [{ type: Output }],
    align: [{ type: Input }],
    allowNegative: [{ type: Input }],
    decimal: [{ type: Input }],
    precision: [{ type: Input }],
    prefix: [{ type: Input }],
    suffix: [{ type: Input }],
    thousands: [{ type: Input }],
    nullable: [{ type: Input }],
    min: [{ type: Input }],
    max: [{ type: Input }],
    required: [{ type: Input }],
    pattern: [{ type: Input }],
    validator: [{ type: Input }],
    _inlineError: [{ type: Input, args: ['inlineError',] }],
    disabled: [{ type: Input }],
    sdSuffix: [{ type: ContentChild, args: [SdSuffixDirective,] }],
    sdLabelDef: [{ type: ContentChild, args: [SdLabelDefDirective,] }],
    tooltip: [{ type: Input }],
    sdChange: [{ type: Output }],
    sdFocus: [{ type: Output }],
    keyupEnter: [{ type: Output }],
    control: [{ type: ViewChild, args: ['control',] }]
};

class SdInputCurrencyTooltipPipe {
    transform(value, tooltip) {
        if (typeof (tooltip) === 'string') {
            return tooltip;
        }
        return tooltip(value);
    }
}
SdInputCurrencyTooltipPipe.decorators = [
    { type: Pipe, args: [{
                name: 'sdInputCurrencyTooltipPipe'
            },] }
];

class SdInputCurrencyModule {
}
SdInputCurrencyModule.decorators = [
    { type: NgModule, args: [{
                imports: [
                    CommonModule,
                    FormsModule,
                    ReactiveFormsModule,
                    MatFormFieldModule,
                    MatInputModule,
                    MatIconModule,
                    MatTooltipModule,
                    SdCommonModule,
                    SdTranslateModule,
                    NgxCurrencyModule
                ],
                declarations: [
                    SdInputCurrency,
                    SdInputCurrencyTooltipPipe
                ],
                exports: [
                    SdInputCurrency,
                    SdInputCurrencyTooltipPipe
                ]
            },] }
];

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

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

export { SdInputCurrency, SdInputCurrencyModule, SdInputCurrencyTooltipPipe };
//# sourceMappingURL=sd-angular-core-input-currency.js.map
