import * as i0 from '@angular/core';
import { EventEmitter, forwardRef, Directive, Input, HostBinding, Output, NgModule } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { CurrencyMaskDirective } from 'ng2-currency-mask';
import { first } from 'rxjs/operators';
import * as i1 from '@seniorsistemas/angular-components/locale';
import { CommonModule } from '@angular/common';

/**
 * @deprecated Should use 'AlignmentOptions' from @seniorsistemas/ng2-currency-mask instead
 */
var NumberAlignmentOption;
(function (NumberAlignmentOption) {
    NumberAlignmentOption["RIGHT"] = "right";
    NumberAlignmentOption["LEFT"] = "left";
})(NumberAlignmentOption || (NumberAlignmentOption = {}));
/**
 * @deprecated Should use BigNumberInput directive instead
 */
class NumberInputDirective extends CurrencyMaskDirective {
    _elementRef;
    localeService;
    precision = 15;
    scale = 0;
    decimalSeparator;
    thousandsSeparator;
    alignTo = NumberAlignmentOption.LEFT;
    allowNegative = true;
    placeholder;
    maxLength;
    pasteRejected = new EventEmitter();
    pasteListener;
    _maxLength = 0;
    keypressListener;
    constructor(_elementRef, _keyValueDiffers, localeService) {
        super({}, _elementRef, _keyValueDiffers);
        this._elementRef = _elementRef;
        this.localeService = localeService;
        this.onLocaleService();
    }
    ngOnInit() {
        this.updateVariables();
        super.ngOnInit();
        this.pasteListener = this._onPaste.bind(this);
        this._elementRef.nativeElement.addEventListener("paste", this.pasteListener);
        this.keypressListener = this._onKeypress.bind(this);
        this._elementRef.nativeElement.addEventListener("keypress", this.keypressListener);
    }
    ngOnChanges(changes) {
        const placeholderChange = changes['placeholder'] && changes['placeholder'].currentValue;
        if (!placeholderChange && this.scale)
            this.placeholder = `0${this.decimalSeparator}${''.padEnd(this.scale, '0')}`;
        if (changes['scale'] ||
            changes['decimalSeparator'] ||
            changes['thousandsSeparator'] ||
            changes['alignTo'] ||
            changes['precision'] ||
            changes['allowNegative']) {
            this.updateVariables();
        }
    }
    ngOnDestroy() {
        this._elementRef.nativeElement.removeEventListener("paste", this.pasteListener);
        this._elementRef.nativeElement.removeEventListener("keypress", this.keypressListener);
    }
    _onPaste(event) {
        const pastedText = event.clipboardData?.getData("text") ?? "";
        const numericText = pastedText.replace(new RegExp(`\\${this.thousandsSeparator}`, "g"), "").replace(this.decimalSeparator, ".");
        const [intPart, decimalPart = ""] = numericText.split(".");
        const totalDigits = intPart.replace(/\D/g, "").length + decimalPart.slice(0, this.scale).length;
        if (totalDigits > this.precision) {
            event.preventDefault();
            event.stopPropagation();
            this.pasteRejected.emit(pastedText);
        }
    }
    _onKeypress(event) {
        const code = event.code;
        if (code === "Minus" || code === "NumpadSubtract") {
            if (this.allowNegative) {
                this.maxLength = this._maxLength + 1;
            }
        }
        else if (code === "Equal" || code === "NumpadAdd") {
            this.maxLength = this._maxLength;
        }
    }
    /**
     * Update the options values according to the directive input values.
     */
    updateVariables() {
        this.options = {
            align: this.alignTo,
            decimal: this.decimalSeparator,
            thousands: this.thousandsSeparator,
            precision: this.scale || 0,
            prefix: '',
            suffix: '',
            allowNegative: this.allowNegative,
        };
        this.calculateMaxLength();
    }
    /**
     * Responsible to calculate the field maximum length considering the separators.
     */
    calculateMaxLength() {
        const decSepLength = this.decimalSeparator?.length ?? 0;
        const thoSepLength = this.thousandsSeparator?.length ?? 0;
        let maxLength = this.precision + (this.scale ? decSepLength : 0);
        maxLength += Math.ceil((this.precision - (this.scale ? this.scale : 0)) / 3 - 1) * thoSepLength;
        this.maxLength = maxLength;
    }
    onLocaleService() {
        this.localeService
            .getLocale()
            .pipe(first())
            .subscribe(() => {
            this.decimalSeparator = this.decimalSeparator ?? this.localeService.getDecimalSeparator();
            this.thousandsSeparator = this.thousandsSeparator ?? this.localeService.getGroupingSeparator();
        });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: NumberInputDirective, deps: [{ token: i0.ElementRef }, { token: i0.KeyValueDiffers }, { token: i1.LocaleService }], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "18.2.14", type: NumberInputDirective, selector: "input[sNumberInput]", inputs: { precision: "precision", scale: "scale", decimalSeparator: "decimalSeparator", thousandsSeparator: "thousandsSeparator", alignTo: "alignTo", allowNegative: "allowNegative", placeholder: "placeholder" }, outputs: { pasteRejected: "pasteRejected" }, host: { properties: { "attr.placeholder": "this.placeholder", "attr.maxLength": "this.maxLength" } }, providers: [
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => NumberInputDirective),
                multi: true,
            },
        ], usesInheritance: true, usesOnChanges: true, ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: NumberInputDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: 'input[sNumberInput]',
                    providers: [
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: forwardRef(() => NumberInputDirective),
                            multi: true,
                        },
                    ],
                }]
        }], ctorParameters: () => [{ type: i0.ElementRef }, { type: i0.KeyValueDiffers }, { type: i1.LocaleService }], propDecorators: { precision: [{
                type: Input
            }], scale: [{
                type: Input
            }], decimalSeparator: [{
                type: Input
            }], thousandsSeparator: [{
                type: Input
            }], alignTo: [{
                type: Input
            }], allowNegative: [{
                type: Input
            }], placeholder: [{
                type: Input
            }, {
                type: HostBinding,
                args: ['attr.placeholder']
            }], maxLength: [{
                type: HostBinding,
                args: ['attr.maxLength']
            }], pasteRejected: [{
                type: Output
            }] } });

/**
 * @deprecated Should use 'BignumberInputModule' instead
 */
class NumberInputModule {
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: NumberInputModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
    static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: NumberInputModule, declarations: [NumberInputDirective], imports: [CommonModule], exports: [NumberInputDirective] });
    static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: NumberInputModule, imports: [CommonModule] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: NumberInputModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [CommonModule],
                    declarations: [NumberInputDirective],
                    exports: [NumberInputDirective],
                }]
        }] });

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

export { NumberAlignmentOption, NumberInputDirective, NumberInputModule };
//# sourceMappingURL=seniorsistemas-angular-components-number-input.mjs.map
