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
     */
    async _initialize() {
        if (!this.form) {
            return;
        }
        const options = this.form.value;
        const name = options.name ?? '';
        const result = (await 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 = configuration.configurableProperties ?? {};
        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;
        this.usedComponentsForms = {};
        for (const cmpId in this.usedProperties) {
            for (const modelName in this.usedProperties[cmpId]) {
                const model = this.customComponentContentMetadata[cmpId]?.editorMetadata.metaInfo?.optionsMetadata?.propertiesMetadata.find(itm => itm.modelType.name == modelName)?.modelType;
                const usedProperties = this.usedProperties[cmpId][modelName];
                if (!model) {
                    continue;
                }
                const options = extend(true, {}, this.customComponentContentMetadata[cmpId]?.editorMetadata.metaInfo?.defaultOptions, this.customComponentContentMetadata[cmpId]?.metadata.options, this.form?.controls.contentOptions.value[cmpId]);
                (_a = this.usedComponentsForms)[cmpId] ?? (_a[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 => {
                    const currentOpts = this.form?.controls.contentOptions.value ?? {};
                    currentOpts[cmpId] ?? (currentOpts[cmpId] = {});
                    extend(currentOpts[cmpId], value);
                    this.form?.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