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

var _name, _form, _pattern, _validator, _autoHeight_1, _subscription, _onChange, _onInput, _updateValidator, _customValidator;
class SdTextarea {
    constructor(ref, formConfig) {
        this.ref = ref;
        this.formConfig = formConfig;
        _name.set(this, v4());
        _form.set(this, void 0);
        this.rows = 5;
        this.modelChange = new EventEmitter();
        this.sdChange = new EventEmitter();
        // Optional
        this.disableErrorMessage = false;
        this.required = false;
        _pattern.set(this, void 0);
        _validator.set(this, void 0);
        _autoHeight_1.set(this, false);
        this.isFocused = false;
        this.formControl = new SdFormControl();
        _subscription.set(this, new Subscription());
        this.onFocus = () => {
            this.isFocused = true;
        };
        this.onBlur = () => {
            var _a;
            this.isFocused = false;
            const val = ((_a = this.formControl.value) !== null && _a !== void 0 ? _a : '').toString();
            if (val.length > val.trim().length) {
                this.formControl.setValue(val.trim());
            }
        };
        this.onClick = () => {
            var _a;
            if ((_a = this.sdView) === null || _a === void 0 ? void 0 : _a.templateRef) {
                if (!this.formControl.disabled && !this.isFocused) {
                    this.focus();
                }
            }
        };
        this.blur = () => {
            var _a, _b;
            (_b = (_a = this.textarea) === null || _a === void 0 ? void 0 : _a.nativeElement) === null || _b === void 0 ? void 0 : _b.blur();
        };
        this.focus = () => {
            this.isFocused = true;
            setTimeout(() => {
                var _a, _b;
                (_b = (_a = this.textarea) === null || _a === void 0 ? void 0 : _a.nativeElement) === null || _b === void 0 ? void 0 : _b.focus();
            }, 100);
        };
        _onChange.set(this, (value) => {
            if (__classPrivateFieldGet(this, _autoHeight_1)) {
                this.textarea.nativeElement.style.height = 'auto';
                this.textarea.nativeElement.style.height = (this.textarea.nativeElement.scrollHeight) + 'px';
            }
            this.modelChange.emit(value);
            this.sdChange.emit(value);
        });
        _onInput.set(this, function () {
            // this.style.height = 'auto';
            // this.style.height = (this.scrollHeight) + 'px';
        });
        _updateValidator.set(this, () => {
            this.formControl.clearValidators();
            this.formControl.clearAsyncValidators();
            const validators = [];
            const asyncValidators = [];
            if (this.required) {
                validators.push(Validators.required);
            }
            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();
        });
        _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 form(val) {
        if (val) {
            if (val instanceof NgForm) {
                __classPrivateFieldSet(this, _form, val.form);
            }
            else {
                __classPrivateFieldSet(this, _form, val);
            }
        }
    }
    set _label(val) {
        this.label = val;
        this.qcId = hash({
            selector: 'sd-textarea',
            label: val
        });
    }
    ;
    set model(value) {
        if (this.formControl.value !== value) {
            this.formControl.setValue(value);
        }
    }
    set _disableErrorMessage(val) {
        this.disableErrorMessage = (val === '') || val;
    }
    set _required(val) {
        this.required = (val === '') || val;
        __classPrivateFieldGet(this, _updateValidator).call(this);
    }
    set _maxlength(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);
    }
    set disabled(val) {
        val = (val === '') || val;
        if (val) {
            this.formControl.disable();
        }
        else {
            this.formControl.enable();
        }
    }
    set _autoHeight(val) {
        __classPrivateFieldSet(this, _autoHeight_1, (val === '') || val);
    }
    ngOnInit() {
        var _a, _b;
        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, _subscription).add(this.formControl.valueChanges.subscribe(__classPrivateFieldGet(this, _onChange)));
        (_b = __classPrivateFieldGet(this, _form)) === null || _b === void 0 ? void 0 : _b.addControl(__classPrivateFieldGet(this, _name), this.formControl);
    }
    ngAfterViewInit() {
        var _a, _b, _c, _d;
        if (__classPrivateFieldGet(this, _autoHeight_1)) {
            (_b = (_a = this.textarea) === null || _a === void 0 ? void 0 : _a.nativeElement) === null || _b === void 0 ? void 0 : _b.setAttribute('style', `height: ${(_d = (_c = this.textarea) === null || _c === void 0 ? void 0 : _c.nativeElement) === null || _d === void 0 ? void 0 : _d.scrollHeight}px;overflow-y:hidden;`);
        }
    }
    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(), _pattern = new WeakMap(), _validator = new WeakMap(), _autoHeight_1 = new WeakMap(), _subscription = new WeakMap(), _onChange = new WeakMap(), _onInput = new WeakMap(), _updateValidator = new WeakMap(), _customValidator = new WeakMap();
SdTextarea.decorators = [
    { type: Component, args: [{
                selector: 'sd-textarea',
                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\"\r\n    *ngIf=\"required\">*</span></label>\r\n<div class=\"d-flex align-items-center\" [class.sd-view]=\"sdView?.templateRef\" [class.c-focused]=\"isFocused\"\r\n  [class.c-disabled]=\"formControl.disabled\" (click)=\"onClick()\">\r\n  <ng-container *ngIf=\"sdView?.templateRef && !isFocused; else default\">\r\n    <ng-container *ngTemplateOutlet=\"sdView.templateRef;context: { value: formControl.value }\">\r\n    </ng-container>\r\n  </ng-container>\r\n  <ng-template #default>\r\n    <mat-form-field appearance=\"outline\" [class.c-no-label]=\"!label\">\r\n      <mat-label *ngIf=\"appearance && label\">{{ label }}</mat-label>\r\n      <textarea matInput [placeholder]=\"placeholder || (appearance ? label : '')\" [formControl]=\"formControl\"\r\n        [required]=\"required\" autocomplete=\"off\" (focus)=\"onFocus()\" (blur)=\"onBlur()\" [rows]=\"rows\"\r\n        [maxlength]=\"maxlength\" [attr.data-qclabel]=\"label\" [attr.data-qcid]=\"qcId\" #textarea></textarea>\r\n      <span *ngIf=\"maxlength && !formControl.disabled\" matSuffix>{{formControl?.value?.length ||\r\n        0}}/{{maxlength}}</span>\r\n      <mat-error *ngIf=\"formControl.touched && formControl.errors?.required\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\">{{ \"This field is required\" | sdTranslate }}</ng-container>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl.touched && formControl.errors?.maxlength\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\">{{'Max length' | sdTranslate}} <strong>{{maxlength}}</strong>\r\n        </ng-container>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl.touched && formControl.errors?.pattern\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\">{{'Pattern error' | sdTranslate}}</ng-container>\r\n      </mat-error>\r\n      <mat-error *ngIf=\"formControl.touched && formControl.errors?.customValidator\">\r\n        <ng-container *ngIf=\"!disableErrorMessage\">{{formControl.errors?.customValidator}}</ng-container>\r\n      </mat-error>\r\n    </mat-form-field>\r\n  </ng-template>\r\n</div>",
                styles: [":host ::ng-deep textarea.mat-input-element{resize:none}:host ::ng-deep .mat-form-field.c-no-label .mat-form-field-infix{border-top: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 textarea.mat-input-element:disabled{color:#4d4d4d!important}:host ::ng-deep .mat-form-field .mat-placeholder-required{color:#f82c13}.sd-view:not(.c-focused):not(.c-disabled):hover{background-color:#ebecf0}"]
            },] }
];
SdTextarea.ctorParameters = () => [
    { type: ChangeDetectorRef },
    { type: undefined, decorators: [{ type: Inject, args: [FORM_CONFIG,] }, { type: Optional }] }
];
SdTextarea.propDecorators = {
    name: [{ type: Input }],
    appearance: [{ type: Input }],
    form: [{ type: Input }],
    _label: [{ type: Input, args: ['label',] }],
    placeholder: [{ type: Input }],
    rows: [{ type: Input }],
    model: [{ type: Input }],
    modelChange: [{ type: Output }],
    sdChange: [{ type: Output }],
    _disableErrorMessage: [{ type: Input, args: ['disableErrorMessage',] }],
    _required: [{ type: Input, args: ['required',] }],
    _maxlength: [{ type: Input, args: ['maxlength',] }],
    pattern: [{ type: Input }],
    validator: [{ type: Input }],
    disabled: [{ type: Input }],
    _autoHeight: [{ type: Input, args: ['autoHeight',] }],
    textarea: [{ type: ViewChild, args: ['textarea',] }],
    sdView: [{ type: ContentChild, args: [SdViewDefDirective,] }],
    sdLabelDef: [{ type: ContentChild, args: [SdLabelDefDirective,] }]
};

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

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

export { SdTextarea, SdTextareaModule };
//# sourceMappingURL=sd-angular-core-textarea.js.map
