import * as i0 from '@angular/core';
import { Component, Directive, Optional, Host, Input, NgModule } from '@angular/core';
import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import { ErrorMessageBaseComponent } from '@ironsource/fusion-ui/components/error-message/common/base';
import { isString } from '@ironsource/fusion-ui/utils';
import { FormControlStatus, ERROR_MESSAGES } from '@ironsource/fusion-ui/components/error-message/common/entities';
export * from '@ironsource/fusion-ui/components/error-message/common/entities';
import * as i1$1 from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import * as i4 from '@ironsource/fusion-ui/services/log';
import * as i3 from '@ironsource/fusion-ui/components/dropdown/v2';
import * as i2 from '@ironsource/fusion-ui/components/input/v2';

function ErrorMessageComponent_div_0_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "div", 1);
} if (rf & 2) {
    const ctx_r0 = i0.ɵɵnextContext();
    i0.ɵɵproperty("ngStyle", ctx_r0.styles)("innerHTML", ctx_r0.errorMessage, i0.ɵɵsanitizeHtml);
} }
class ErrorMessageComponent extends ErrorMessageBaseComponent {
    static { this.ɵfac = /*@__PURE__*/ (() => { let ɵErrorMessageComponent_BaseFactory; return function ErrorMessageComponent_Factory(t) { return (ɵErrorMessageComponent_BaseFactory || (ɵErrorMessageComponent_BaseFactory = i0.ɵɵgetInheritedFactory(ErrorMessageComponent)))(t || ErrorMessageComponent); }; })(); }
    static { this.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: ErrorMessageComponent, selectors: [["fusion-error-message"]], features: [i0.ɵɵInheritDefinitionFeature], decls: 1, vars: 1, consts: [["class", "fusion-error", 3, "ngStyle", "innerHTML", 4, "ngIf"], [1, "fusion-error", 3, "ngStyle", "innerHTML"]], template: function ErrorMessageComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵtemplate(0, ErrorMessageComponent_div_0_Template, 1, 2, "div", 0);
        } if (rf & 2) {
            i0.ɵɵproperty("ngIf", ctx.showError);
        } }, dependencies: [i1.NgIf, i1.NgStyle], styles: ["[_nghost-%COMP%]   .fusion-error[_ngcontent-%COMP%]{font-size:11px;font-family:HelveticaNeue,helvetica,sans-serif;font-weight:400}[_nghost-%COMP%]   .fusion-error[_ngcontent-%COMP%]{margin-top:5px;line-height:14px;color:var(--fu-negative-700, #da564f)}"] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ErrorMessageComponent, [{
        type: Component,
        args: [{ selector: 'fusion-error-message', template: "<div class=\"fusion-error\" *ngIf=\"showError\" [ngStyle]=\"styles\" [innerHTML]=\"errorMessage\"></div>\n", styles: [":host .fusion-error{font-size:11px;font-family:HelveticaNeue,helvetica,sans-serif;font-weight:400}:host .fusion-error{margin-top:5px;line-height:14px;color:var(--fu-negative-700, #da564f)}\n"] }]
    }], null, null); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(ErrorMessageComponent, { className: "ErrorMessageComponent", filePath: "error-message.component.ts", lineNumber: 9 }); })();

class ErrorMessageDirective {
    constructor(elementRef, viewContainerRef, changeDetectorRef, fg, inputComponent, dropdownComponent, loggerService) {
        this.elementRef = elementRef;
        this.viewContainerRef = viewContainerRef;
        this.changeDetectorRef = changeDetectorRef;
        this.fg = fg;
        this.inputComponent = inputComponent;
        this.dropdownComponent = dropdownComponent;
        this.loggerService = loggerService;
        this.errorStyles = {};
    }
    get parentFormControl() {
        return this.fg.formDirective ? this.fg.formDirective.form : null;
    }
    ngOnInit() {
        this.customMessages = this.customMessages || {};
        this.customMapping = this.customMapping || {};
        const showErrorInit = this.showError;
        this.showError = this.showError === undefined || this.showError === null ? true : this.showError;
        this.errorMessageComponent = this.viewContainerRef.createComponent(ErrorMessageComponent);
        this.errorMessageComponent.instance.styles = this.errorStyles;
        this.formControl = this.parentFormControl.get(this.elementRef.nativeElement.getAttribute('formcontrolname'));
        this.isTooltipMessage = this.elementRef.nativeElement.getAttribute('errortype');
        this.formControl.valueChanges.subscribe(() => {
            this._checkErrors();
        });
        this.formControl.statusChanges.subscribe((status) => {
            // handle async validations
            if (status === FormControlStatus.Invalid && this.currentStatus === FormControlStatus.Pending) {
                this._checkErrors(true);
            }
            this.currentStatus = status;
        });
        if (showErrorInit) {
            this._checkErrors();
        }
    }
    ngOnChanges() {
        this.viewContainerRef.clear();
        this._checkErrors();
    }
    ngOnDestroy() {
        if (this.errorMessageComponent) {
            this.errorMessageComponent.destroy();
        }
    }
    _setComponentError(error) {
        if (this.inputComponent) {
            this.inputComponent.error = error;
            this.inputComponent.toggleErrorClass(!!error);
        }
        else if (this.dropdownComponent) {
            this.dropdownComponent.error = error;
        }
    }
    _checkErrors(async) {
        if (this.errorMessageComponent) {
            let errorMessage = '';
            this.errorMessageComponent.instance.showError = false;
            this._setComponentError('');
            const errors = this.formControl.errors || {};
            const isFormControlInvalid = Object.keys(errors).some(errorKey => {
                // if error value is string to that's the message will be shown
                errorMessage = isString(errors[errorKey]) ? errors[errorKey] : this._getMessage(errorKey);
                return true;
            });
            if (isFormControlInvalid && this.showError) {
                if (this.isTooltipMessage) {
                    this._setComponentError(errorMessage);
                }
                else {
                    this.errorMessageComponent.instance.errorMessage = errorMessage;
                    this.errorMessageComponent.instance.showError = this.showError;
                    if (this.inputComponent) {
                        this.inputComponent.error = this.errorMessageComponent.instance.showError;
                        this.inputComponent.toggleErrorClass(this.errorMessageComponent.instance.showError);
                    }
                }
            }
            if (async) {
                this.changeDetectorRef.detectChanges();
                this.errorMessageComponent.changeDetectorRef.detectChanges();
            }
        }
    }
    _getMessage(errorKey) {
        let errorMessage = '';
        if (this.customMessages[errorKey]) {
            errorMessage = this.customMessages[errorKey];
        }
        else if (ERROR_MESSAGES[errorKey]) {
            errorMessage = ERROR_MESSAGES[errorKey];
            errorMessage = errorMessage.replace('{NAME}', this.fusionErrorMessage);
            errorMessage = errorMessage.replace('{INNER-NAME}', this.errorInnerMessage || this.fusionErrorMessage);
            Object.keys(this.customMapping).forEach(find => (errorMessage = errorMessage.replace(`{${find}}`, this.customMapping[find])));
        }
        else {
            this.loggerService.error(new Error(`Unknown validation message for error key: ${errorKey}`));
        }
        return errorMessage;
    }
    static { this.ɵfac = function ErrorMessageDirective_Factory(t) { return new (t || ErrorMessageDirective)(i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(i0.ViewContainerRef), i0.ɵɵdirectiveInject(i0.ChangeDetectorRef), i0.ɵɵdirectiveInject(i1$1.ControlContainer), i0.ɵɵdirectiveInject(i2.InputComponent, 9), i0.ɵɵdirectiveInject(i3.DropdownComponent, 9), i0.ɵɵdirectiveInject(i4.LogService)); }; }
    static { this.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective({ type: ErrorMessageDirective, selectors: [["", "fusionErrorMessage", ""]], inputs: { showError: "showError", fusionErrorMessage: "fusionErrorMessage", errorInnerMessage: "errorInnerMessage", customMessages: "customMessages", customMapping: "customMapping", errorStyles: "errorStyles" }, features: [i0.ɵɵNgOnChangesFeature] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ErrorMessageDirective, [{
        type: Directive,
        args: [{
                selector: '[fusionErrorMessage]'
            }]
    }], () => [{ type: i0.ElementRef }, { type: i0.ViewContainerRef }, { type: i0.ChangeDetectorRef }, { type: i1$1.ControlContainer }, { type: i2.InputComponent, decorators: [{
                type: Optional
            }, {
                type: Host
            }] }, { type: i3.DropdownComponent, decorators: [{
                type: Optional
            }, {
                type: Host
            }] }, { type: i4.LogService }], { showError: [{
            type: Input
        }], fusionErrorMessage: [{
            type: Input
        }], errorInnerMessage: [{
            type: Input
        }], customMessages: [{
            type: Input
        }], customMapping: [{
            type: Input
        }], errorStyles: [{
            type: Input
        }] }); })();

class ErrorMessageModule {
    static { this.ɵfac = function ErrorMessageModule_Factory(t) { return new (t || ErrorMessageModule)(); }; }
    static { this.ɵmod = /*@__PURE__*/ i0.ɵɵdefineNgModule({ type: ErrorMessageModule }); }
    static { this.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ imports: [CommonModule, ReactiveFormsModule] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ErrorMessageModule, [{
        type: NgModule,
        args: [{
                imports: [CommonModule, ReactiveFormsModule],
                declarations: [ErrorMessageDirective, ErrorMessageComponent],
                exports: [ErrorMessageDirective]
            }]
    }], null, null); })();
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(ErrorMessageModule, { declarations: [ErrorMessageDirective, ErrorMessageComponent], imports: [CommonModule, ReactiveFormsModule], exports: [ErrorMessageDirective] }); })();

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

export { ErrorMessageDirective, ErrorMessageModule };
//# sourceMappingURL=ironsource-fusion-ui-components-error-message-v2.mjs.map
