import { EventEmitter, Component, ChangeDetectorRef, Input, Output, 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 { FormControl, Validators, NgForm, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { v4 } from 'uuid';
import { SdCurrencyPipe } from '@sd-angular/core/utility';
import { startWith } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { SdTranslateModule } from '@sd-angular/core/translate';

var _name, _form, _model, _pattern, _validator, _subscription, _updateValidator, _onChange, _customValidator;
class SdInput {
    constructor(ref, currencyPipe) {
        this.ref = ref;
        this.currencyPipe = currencyPipe;
        _name.set(this, v4());
        _form.set(this, void 0);
        this.type = 'text';
        this.step = 0.01;
        _model.set(this, void 0);
        this.modelChange = new EventEmitter();
        // Validator
        this.isRequired = false;
        _pattern.set(this, void 0);
        _validator.set(this, void 0);
        this.icon = 'search';
        this.sdClick = new EventEmitter();
        this.sdChange = new EventEmitter();
        this.sdFocus = new EventEmitter();
        this.sdFocusForceBlur = new EventEmitter();
        this.keyupEnter = new EventEmitter();
        this.formControl = new FormControl();
        _subscription.set(this, new Subscription());
        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 (this.minlength > 0) {
                validators.push(Validators.minLength(this.minlength));
            }
            if (this.maxlength > 0) {
                validators.push(Validators.maxLength(this.maxlength));
            }
            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)));
            }
            this.formControl.setValidators(validators);
            this.formControl.setAsyncValidators(asyncValidators);
            this.formControl.updateValueAndValidity();
        });
        _onChange.set(this, (value) => {
            this.modelChange.emit(value);
            this.sdChange.emit(value);
        });
        this.onKeyupEnter = () => {
            this.keyupEnter.emit(this.formControl.value);
        };
        this.onClick = () => {
            this.sdClick.emit(this.formControl.value);
        };
        this.onFocus = () => {
            var _a;
            this.sdFocus.emit();
            if (((_a = this.sdFocusForceBlur.observers) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                this.blur();
                this.sdFocusForceBlur.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.blur = () => {
            var _a, _b;
            (_b = (_a = this.control) === null || _a === void 0 ? void 0 : _a.nativeElement) === null || _b === void 0 ? void 0 : _b.blur();
        };
        _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 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 required(val) {
        this.isRequired = (val === '') || val;
        __classPrivateFieldGet(this, _updateValidator).call(this);
    }
    set pMinlength(val) {
        this.minlength = +val;
        __classPrivateFieldGet(this, _updateValidator).call(this);
    }
    set pMaxlength(val) {
        this.maxlength = +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);
    }
    // Optional
    set disabled(val) {
        val = (val === '') || val;
        if (val) {
            this.formControl.disable();
        }
        else {
            this.formControl.enable();
        }
    }
    ngOnInit() {
    }
    ngAfterViewInit() {
        var _a;
        __classPrivateFieldGet(this, _subscription).add(this.formControl.valueChanges.pipe(startWith(__classPrivateFieldGet(this, _model))).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();
    }
}
_name = new WeakMap(), _form = new WeakMap(), _model = new WeakMap(), _pattern = new WeakMap(), _validator = new WeakMap(), _subscription = new WeakMap(), _updateValidator = new WeakMap(), _onChange = new WeakMap(), _customValidator = new WeakMap();
SdInput.decorators = [
    { type: Component, args: [{
                selector: 'sd-input',
                template: "<div class=\"d-flex align-items-center\">\r\n  <div class=\"mat-label mr-12 mb-12\" *ngIf=\"leftLabel\" [ngStyle]=\"{'min-width': labelMinWidth}\">{{leftLabel}}</div>\r\n  <div class=\"media-body\">\r\n    <mat-form-field class=\"sd-md\" [ngClass]=\"{'sd-form-tooltip':tooltip, 'sd-sm': size === 'sm'}\" appearance=\"outline\">\r\n      <mat-label *ngIf=\"label && !leftLabel\">{{label}}</mat-label>\r\n      <input [formControl]=\"formControl\" [type]=\"type\" #control matInput\r\n        [placeholder]=\"placeholder || label\" (keyup.enter)=\"onKeyupEnter()\" (focus)=\"onFocus()\" (blur)=\"onBlur()\"\r\n        [required]=\"isRequired\" autocomplete=\"off\">\r\n      <span class=\"mr-1\" *ngIf=\"maxlength\" matSuffix>{{formControl.value?.length || 0}}/{{maxlength}}</span>\r\n      <mat-icon *ngIf=\"!formControl.disabled && sdClick?.observers?.length\" (click)=\"onClick()\"\r\n        class=\"pointer sd-suffix-icon\" matSuffix>\r\n        {{icon}}\r\n      </mat-icon>\r\n      <mat-error *ngIf=\"formControl.errors?.required\">\r\n        {{'This field is required' | sdTranslate}}\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl.errors?.maxlength\">\r\n        {{'Max length' | sdTranslate}} <strong>{{maxlength}}</strong>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl.errors?.pattern\">\r\n        {{'Pattern error' | sdTranslate}}\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl.errors?.customValidator\">\r\n        <strong>{{formControl.errors?.customValidator}}</strong>\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 | sdInputTooltipPipe:tooltip\" matSuffix\r\n        #sdTooltip=\"matTooltip\">info</mat-icon>\r\n    </div>\r\n  </div>\r\n\r\n</div>",
                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}"]
            },] }
];
SdInput.ctorParameters = () => [
    { type: ChangeDetectorRef },
    { type: SdCurrencyPipe }
];
SdInput.propDecorators = {
    size: [{ type: Input }],
    form: [{ type: Input }],
    label: [{ type: Input }],
    placeholder: [{ type: Input }],
    type: [{ type: Input }],
    step: [{ type: Input }],
    leftLabel: [{ type: Input }],
    labelMinWidth: [{ type: Input }],
    model: [{ type: Input }],
    modelChange: [{ type: Output }],
    required: [{ type: Input }],
    pMinlength: [{ type: Input, args: ['minlength',] }],
    pMaxlength: [{ type: Input, args: ['maxlength',] }],
    pattern: [{ type: Input }],
    validator: [{ type: Input }],
    disabled: [{ type: Input }],
    icon: [{ type: Input }],
    tooltip: [{ type: Input }],
    sdClick: [{ type: Output }],
    sdChange: [{ type: Output }],
    sdFocus: [{ type: Output }],
    sdFocusForceBlur: [{ type: Output }],
    keyupEnter: [{ type: Output }],
    control: [{ type: ViewChild, args: ['control',] }]
};

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

class SdInputModule {
}
SdInputModule.decorators = [
    { type: NgModule, args: [{
                imports: [
                    CommonModule,
                    FormsModule,
                    ReactiveFormsModule,
                    MatFormFieldModule,
                    MatInputModule,
                    MatIconModule,
                    MatTooltipModule,
                    SdTranslateModule
                ],
                declarations: [
                    SdInput,
                    SdInputTooltipPipe
                ],
                exports: [
                    SdInput,
                    SdInputTooltipPipe
                ]
            },] }
];

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

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

export { SdInput, SdInputModule, SdInputTooltipPipe };
//# sourceMappingURL=sd-angular-core-input-dropdown.js.map
