import { __awaiter } from "tslib";
import { ChangeDetectionStrategy, Component, inject, Injector } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormModelBuilder } from '@anglr/common/forms';
import { PropertiesControlBase, PropertiesControlsModule } from '@anglr/dynamic/layout-editor';
import { extend } from '@jscrpt/common';
import { GetControlsSAPipe } from '../../pipes/getControls/getControls.pipe';
import { GetModelSAPipe, PropertiesMetadataSAPipe } from '../../../../../pipes';
import { getCustomComponentMeta } from '../../../../../misc/utils';
import { CustomComponentsRegister } from '../../../../../services';
import * as i0 from "@angular/core";
import * as i1 from "@angular/common";
import * as i2 from "../../../../../../../layout-editor/src/modules/propertiesControls/directives/propertiesControlRenderer/propertiesControlRenderer.directive";
/**
 * Component used for displaying editation of content options
 */
export class ContentOptionsPropertiesControlSAComponent extends PropertiesControlBase {
    constructor() {
        super(...arguments);
        //######################### protected properties #########################
        /**
         * Instance of injector for this component
         */
        this.injector = inject(Injector);
        /**
         * Form model builder
         */
        this.formModelBuilder = inject(FormModelBuilder);
        /**
         * Instance of custom components register
         */
        this.customComponentsRegister = inject(CustomComponentsRegister);
        /**
         * Metadata for each component in custom component
         */
        this.customComponentContentMetadata = {};
        /**
         * Represents used properties
         */
        this.usedProperties = {};
        /**
         * Stores components and their form groups
         */
        this.usedComponentsForms = {};
    }
    //######################### protected methods - overrides #########################
    /**
     * @inheritdoc
     */
    _initialize() {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.form) {
                return;
            }
            const options = this.form.value;
            const name = (_a = options.name) !== null && _a !== void 0 ? _a : '';
            const result = (yield getCustomComponentMeta(name, this.injector));
            if (!result) {
                return;
            }
            this.customComponentContentMetadata = result.contentMetadata;
            this.customComponentMetadata = result.metadata;
            const configuration = this.customComponentsRegister.getConfigurationForComponent(name);
            if (!configuration) {
                return;
            }
            this.usedProperties = (_b = configuration.configurableProperties) !== null && _b !== void 0 ? _b : {};
            for (const id in this.usedProperties) {
                if (!this.customComponentContentMetadata[id]) {
                    delete this.usedProperties[id];
                }
                //TODO: remove models that are not present in metadata, and also properties
                // for(const modelName in this.usedProperties[id])
                // {
                //     if(!this.customComponentContentMetadata[id]?.editorMetadata.metaInfo?.optionsMetadata?.propertiesMetadata)
                // }
            }
            this.initForms();
        });
    }
    //######################### protected methods #########################
    /**
     * Initialize forms for properties
     */
    initForms() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        var _k;
        this.usedComponentsForms = {};
        for (const cmpId in this.usedProperties) {
            for (const modelName in this.usedProperties[cmpId]) {
                const model = (_d = (_c = (_b = (_a = this.customComponentContentMetadata[cmpId]) === null || _a === void 0 ? void 0 : _a.editorMetadata.metaInfo) === null || _b === void 0 ? void 0 : _b.optionsMetadata) === null || _c === void 0 ? void 0 : _c.propertiesMetadata.find(itm => itm.modelType.name == modelName)) === null || _d === void 0 ? void 0 : _d.modelType;
                const usedProperties = this.usedProperties[cmpId][modelName];
                if (!model) {
                    continue;
                }
                const options = extend(true, {}, (_f = (_e = this.customComponentContentMetadata[cmpId]) === null || _e === void 0 ? void 0 : _e.editorMetadata.metaInfo) === null || _f === void 0 ? void 0 : _f.defaultOptions, (_g = this.customComponentContentMetadata[cmpId]) === null || _g === void 0 ? void 0 : _g.metadata.options, (_h = this.form) === null || _h === void 0 ? void 0 : _h.controls.contentOptions.value[cmpId]);
                (_j = (_k = this.usedComponentsForms)[cmpId]) !== null && _j !== void 0 ? _j : (_k[cmpId] = {});
                const modelInstance = new model(options);
                for (const property of Object.keys(modelInstance)) {
                    //remove property if not used
                    if (usedProperties.indexOf(property) < 0) {
                        delete modelInstance[property];
                    }
                }
                const form = this.usedComponentsForms[cmpId][modelName] = this.formModelBuilder
                    .build(modelInstance);
                console.log(form);
                form.valueChanges.subscribe(value => {
                    var _a, _b, _c, _d;
                    const currentOpts = (_b = (_a = this.form) === null || _a === void 0 ? void 0 : _a.controls.contentOptions.value) !== null && _b !== void 0 ? _b : {};
                    (_c = currentOpts[cmpId]) !== null && _c !== void 0 ? _c : (currentOpts[cmpId] = {});
                    extend(currentOpts[cmpId], value);
                    (_d = this.form) === null || _d === void 0 ? void 0 : _d.controls.contentOptions.patchValue(currentOpts);
                });
            }
        }
    }
}
ContentOptionsPropertiesControlSAComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: ContentOptionsPropertiesControlSAComponent, deps: null, target: i0.ɵɵFactoryTarget.Component });
ContentOptionsPropertiesControlSAComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "17.0.4", type: ContentOptionsPropertiesControlSAComponent, isStandalone: true, selector: "content-options", providers: [
        FormModelBuilder,
    ], usesInheritance: true, ngImport: i0, template: "<ng-container *ngFor=\"let cmp of usedProperties | keyvalue\">\n    <div class=\"dynamic-margin-top-small dynamic-bold dynamic-text-uppercase dynamic-margin-left-extra-small\">{{customComponentContentMetadata[cmp.key]?.metadata?.displayName}}</div>\n\n    <ng-container *ngFor=\"let modelName of cmp.value | keyvalue\">\n        <ng-container *ngFor=\"let ctrl of modelName.key | getControls: customComponentContentMetadata[cmp.key]\">\n            <ng-container [propertiesControl]=\"ctrl\" [form]=\"usedComponentsForms[cmp.key][modelName.key]\" [propertiesMetadata]=\"modelName.key | getModel: customComponentContentMetadata[cmp.key] | propertiesMetadata\"></ng-container>\n        </ng-container>\n    </ng-container>\n\n    <div class=\"component-separator\"></div>\n</ng-container>", dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "pipe", type: i1.KeyValuePipe, name: "keyvalue" }, { kind: "ngmodule", type: PropertiesControlsModule }, { kind: "directive", type: i2.PropertiesControlRendererDirective, selector: "[propertiesControl]", inputs: ["form", "propertiesMetadata", "propertiesControl"] }, { kind: "pipe", type: GetControlsSAPipe, name: "getControls" }, { kind: "pipe", type: GetModelSAPipe, name: "getModel" }, { kind: "pipe", type: PropertiesMetadataSAPipe, name: "propertiesMetadata" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: ContentOptionsPropertiesControlSAComponent, decorators: [{
            type: Component,
            args: [{ selector: 'content-options', standalone: true, imports: [
                        CommonModule,
                        PropertiesControlsModule,
                        GetControlsSAPipe,
                        GetModelSAPipe,
                        PropertiesMetadataSAPipe,
                    ], providers: [
                        FormModelBuilder,
                    ], changeDetection: ChangeDetectionStrategy.OnPush, template: "<ng-container *ngFor=\"let cmp of usedProperties | keyvalue\">\n    <div class=\"dynamic-margin-top-small dynamic-bold dynamic-text-uppercase dynamic-margin-left-extra-small\">{{customComponentContentMetadata[cmp.key]?.metadata?.displayName}}</div>\n\n    <ng-container *ngFor=\"let modelName of cmp.value | keyvalue\">\n        <ng-container *ngFor=\"let ctrl of modelName.key | getControls: customComponentContentMetadata[cmp.key]\">\n            <ng-container [propertiesControl]=\"ctrl\" [form]=\"usedComponentsForms[cmp.key][modelName.key]\" [propertiesMetadata]=\"modelName.key | getModel: customComponentContentMetadata[cmp.key] | propertiesMetadata\"></ng-container>\n        </ng-container>\n    </ng-container>\n\n    <div class=\"component-separator\"></div>\n</ng-container>" }]
        }] });
//# sourceMappingURL=contentOptionsPropertiesControl.component.js.map