import * as i1 from '@acorex/platform/layout/widget-core';
import { AXPWidgetsCatalog, AXPValueWidgetComponent, AXPWidgetCoreModule, AXPLayoutBaseWidgetComponent, createStringProperty, AXPWidgetGroupEnum, AXP_WIDGETS_ADVANCE_CATEGORY, AXP_WIDGETS_LAYOUT_CATEGORY } from '@acorex/platform/layout/widget-core';
import { AXPDesignerConnector, AXPDesignerService, AXPWidgetDesignerRendererDirective, AXPDesignerAddWidgetMiniButtonComponent, AXPDesignerMessageKeys } from '@acorex/platform/layout/designer';
import { AXP_NAME_PROPERTY, AXP_DATA_PATH_PROPERTY, AXP_BEHAVIOR_PROPERTY_GROUP, AXPWidgetsModule } from '@acorex/platform/layout/widgets';
import * as i2$1 from '@acorex/platform/workflow';
import { AXPWorkflowService, AXPWorkflowAction, AXPWorkflowModule } from '@acorex/platform/workflow';
import { AXPDataGenerator, AXPBroadcastEventService, AXP_MODULE_MANIFEST_PROVIDER } from '@acorex/platform/core';
import { AXPEntityService, AXMEntityCrudServiceImpl, AXP_ENTITY_DEFINITION_LOADER } from '@acorex/platform/layout/entity';
import { AXPSearchCommandProvider, AXPWorkflowNavigateAction, AXP_MENU_PROVIDER, AXP_SETTING_DEFINITION_PROVIDER, AXP_SEARCH_PROVIDER } from '@acorex/platform/common';
import { AXP_PERMISSION_DEFINITION_PROVIDER } from '@acorex/platform/auth';
import * as i0 from '@angular/core';
import { Injectable, inject, Injector, NgModule, InjectionToken, computed, signal, effect, ChangeDetectionStrategy, Component, HostBinding } from '@angular/core';
import { ROUTES } from '@angular/router';
import * as i3 from '@acorex/core/translation';
import { AXTranslationService, AXTranslationModule } from '@acorex/core/translation';
import { AXPCommonMenuKeys } from '@acorex/modules/common';
import { get, sortBy } from 'lodash-es';
import * as i2 from '@angular/common';
import { CommonModule } from '@angular/common';
import { AXPopupService } from '@acorex/components/popup';
import { AXPTemplateViewerService } from '@acorex/platform/layout/components';
import { AXP_IDENTIFIER_RULES } from '@acorex/modules/identifier-management';

const config = {
    i18n: 'form-template-management',
    module: 'FormTemplateManagement',
};
const RootConfig = {
    config,
    module: {
        route: 'form-template-management',
        name: 'FormTemplateManagement',
        title: `@${config.i18n}:module.title`,
        icon: 'fa-light fa-file-invoice'
    },
    entities: {
        template: {
            name: 'Template',
            title: `@${config.i18n}:templates.entities.template.title`,
            source: `${config.module}.Template`,
            icon: 'fa-light fa-file-code'
        }
    },
};

//#region ----   Imports   ----
//#endregion
//#region ----   Manifest Definition   ----
/**
 * Form Template Management Module Manifest.
 * Defines module metadata, features, and provider references.
 */
const FormTemplateManagementManifest = {
    name: RootConfig.module.name,
    version: '1.0.0',
    title: RootConfig.module.title,
    icon: RootConfig.module.icon,
    i18n: RootConfig.config.i18n,
    // Module dependencies (optional)
};
//#endregion

const AXPFormTemplateManagementPermissionKeys = {
    FormTemplate: {
        Templates: {
            Management: 'FormTemplateManagement:Permission:Template.Management',
            View: 'FormTemplateManagement:Permission:Template.View',
            Edit: 'FormTemplateManagement:Permission:Template.Edit',
            Delete: 'FormTemplateManagement:Permission:Template.Delete',
            Create: 'FormTemplateManagement:Permission:Template.Create',
        }
    },
};

class AXMPermissionDefinitionProvider {
    constructor(injector) {
        this.injector = injector;
        this.translateService = this.injector.get(AXTranslationService);
    }
    async define(context) {
        const keys = AXPFormTemplateManagementPermissionKeys.FormTemplate;
        const moduleTitle = await this.translateService.translateAsync('@form-template-management:module.title');
        // Templates permissions
        const templateTrans = async (action) => await this.translateService.translateAsync(`@form-template-management:templates.permissions.templates.actions.${action}.title`);
        // Categories permissions  
        const categoryTrans = async (action) => await this.translateService.translateAsync(`@form-template-management:categories.permissions.categories.actions.${action}.title`);
        context.addGroup(RootConfig.module.name, moduleTitle)
            //  
            .addPermission(keys.Templates.Management, await templateTrans('manage'))
            .addChild(keys.Templates.View, await templateTrans('view'))
            .addChild(keys.Templates.Edit, await templateTrans('edit'))
            .addChild(keys.Templates.Delete, await templateTrans('delete'))
            .addChild(keys.Templates.Create, await templateTrans('create'))
            .endPermission();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMPermissionDefinitionProvider, deps: [{ token: i0.Injector }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMPermissionDefinitionProvider }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMPermissionDefinitionProvider, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: i0.Injector }] });

const AXPFormTemplateManagementMenuKeys = {
    Root: 'FormTemplateManagement:Menu',
    Templates: 'FormTemplateManagement:Menu:Templates',
};

class AXMMenuProvider {
    constructor() {
        this.entityService = inject(AXPEntityService);
    }
    async provide(context) {
        const scope = RootConfig.config.i18n;
        const module = RootConfig.module;
        const formsMenu = context.find(AXPCommonMenuKeys.FormsAndAssessments);
        if (!formsMenu.exists) {
            context.find(AXPCommonMenuKeys.Configuration).addItems([
                {
                    name: AXPCommonMenuKeys.FormsAndAssessments,
                    priority: 8935,
                    text: '@general:menus.forms-and-assessments.title',
                    icon: 'fa-light fa-file-code',
                    type: 'menu',
                    children: [],
                },
            ]);
        }
        context.find(AXPCommonMenuKeys.FormsAndAssessments).addItems([
            {
                name: AXPFormTemplateManagementMenuKeys.Templates,
                text: `@${scope}:templates.menus.forms.title`,
                path: this.entityService.createPath(module.name, RootConfig.entities.template.name),
                icon: RootConfig.entities.template.icon,
                priority: 3,
                policy: {
                    features: [module.name],
                    permissions: [AXPFormTemplateManagementPermissionKeys.FormTemplate.Templates.Management],
                },
            },
        ]);
    }
}

class AXMEntityProvider {
    constructor() {
        this.injector = inject(Injector);
    }
    preload() {
        const module = RootConfig.module.name;
        return Array.from(Object.values(RootConfig.entities)).map((entity) => ({
            module: module,
            entity: entity.name,
        }));
    }
    async get(moduleName, entityName) {
        if (moduleName == RootConfig.module.name) {
            switch (entityName) {
                case RootConfig.entities.template.name:
                    return (await import('./acorex-modules-form-template-management-template.entity-Bvm5t3dD.mjs')).factory(this.injector);
            }
        }
        return null;
    }
    async list() {
        const m = RootConfig.module.name;
        return Promise.resolve(Object.values(RootConfig.entities).map((e) => ({ name: e.name, module: m })));
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMEntityProvider, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMEntityProvider }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMEntityProvider, decorators: [{
            type: Injectable
        }] });

var AXPFormTemplateSettings;
(function (AXPFormTemplateSettings) {
    AXPFormTemplateSettings["HistoryPanel"] = "FormTemplateManagement:Setting:Designer.HistoryPanel";
    AXPFormTemplateSettings["AutoSave"] = "FormTemplateManagement:Setting:Designer.AutoSave";
    AXPFormTemplateSettings["AutoSaveInterval"] = "FormTemplateManagement:Setting:Designer.AutoSaveInterval";
    AXPFormTemplateSettings["AutoSaveTimeout"] = "FormTemplateManagement:Setting:Designer.AutoSaveTimeout";
})(AXPFormTemplateSettings || (AXPFormTemplateSettings = {}));

class AXMSettingProvider {
    constructor(injector) {
        this.injector = injector;
        this.translateService = this.injector.get(AXTranslationService);
    }
    async provide(context) {
        const formTemplateTrans = async (key) => await this.translateService.translateAsync(`@form-template-management:designer.settings.form-template.${key}`);
        const designerTrans = async (key) => await this.translateService.translateAsync(`@form-template-management:designer.settings.designer.${key}`);
        context
            // Add Form Template Group
            .addGroup('form-template', await formTemplateTrans('title'), await formTemplateTrans('description'), RootConfig.module.icon)
            // Start Interface Section
            .addSection('designer', await designerTrans('title'), await designerTrans('description'))
            .addSetting({
            key: AXPFormTemplateSettings.HistoryPanel,
            title: await designerTrans('items.history-panel.title'),
            scope: 'U',
            isInherited: true,
            defaultValue: false,
            widget: {
                type: AXPWidgetsCatalog.toggle,
            },
            description: await designerTrans('items.history-panel.description'),
            validationRules: [
                {
                    rule: 'required',
                },
            ],
        })
            .addSetting({
            key: AXPFormTemplateSettings.AutoSave,
            title: await designerTrans('items.auto-save.title'),
            scope: 'U',
            isInherited: true,
            defaultValue: false,
            widget: {
                type: AXPWidgetsCatalog.toggle,
            },
            description: await designerTrans('items.auto-save.description'),
        })
            .addSetting({
            key: AXPFormTemplateSettings.AutoSaveInterval,
            title: await designerTrans('items.auto-save-interval.title'),
            scope: 'U',
            isInherited: true,
            defaultValue: 1,
            widget: {
                type: AXPWidgetsCatalog.number,
                options: {
                    visibility: `{{ context.eval('designer.auto-save') }}`,
                    hasClearButton: false,
                    minValue: 1,
                    maxValue: 60,
                }
            },
            description: await designerTrans('items.auto-save-interval.description'),
        })
            .endSection()
            // End Form Template Group
            .endGroup();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMSettingProvider, deps: [{ token: i0.Injector }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMSettingProvider }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMSettingProvider, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: i0.Injector }] });

class AXMSearchCommandProvider extends AXPSearchCommandProvider {
    constructor() {
        super(...arguments);
        this.commands = [
            {
                group: 'command',
                title: 'New Form Template',
                icon: RootConfig.entities.template.icon,
                description: 'Create a new form template for designing reusable forms.', // Added description
                command: {
                    // 'create-entity': {
                    //   entity: `${RootConfig.module.name}.${RootConfig.entities.template.name}`,
                    // },
                    name: 'create-entity',
                    options: {
                        entity: `${RootConfig.module.name}.${RootConfig.entities.template.name}`
                    }
                },
            },
        ];
    }
}

class AXMFormTemplateManagementTemplateEntityService extends AXMEntityCrudServiceImpl {
}
class AXMFormTemplateManagementTemplateEntityServiceImpl extends AXMFormTemplateManagementTemplateEntityService {
    constructor() {
        super(`${RootConfig.module.name}.${RootConfig.entities.template.name}`);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementTemplateEntityServiceImpl, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementTemplateEntityServiceImpl }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementTemplateEntityServiceImpl, decorators: [{
            type: Injectable
        }], ctorParameters: () => [] });

class AXMFormTemplateManagementTemplateEntityModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementTemplateEntityModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementTemplateEntityModule }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementTemplateEntityModule, providers: [
            {
                provide: AXMFormTemplateManagementTemplateEntityService,
                useClass: AXMFormTemplateManagementTemplateEntityServiceImpl,
            },
        ] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementTemplateEntityModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [],
                    exports: [],
                    declarations: [],
                    providers: [
                        {
                            provide: AXMFormTemplateManagementTemplateEntityService,
                            useClass: AXMFormTemplateManagementTemplateEntityServiceImpl,
                        },
                    ],
                }]
        }] });

const AXMFormTemplateTypes = {
    Form: { id: 10, title: 'Form Template' },
    Widget: { id: 20, title: 'Widget Template' },
    Report: { id: 30, title: 'Report Template' },
};

class AXPTemplateWidgetProviderImpl {
    constructor() {
        this.service = inject(AXMFormTemplateManagementTemplateEntityService);
    }
    async items(query) {
        const result = (await this.service.query(query)).items.map((c) => ({
            id: c.id,
            title: c.title,
            group: {
                name: c.categoryIds[0],
                order: 2,
                title: get(c, 'category.title') ?? 'Custom',
            },
            description: c.description,
        }));
        return result;
    }
    async get(id) {
        const item = await this.service.getOne(id);
        if (item) {
            const document = JSON.parse(item.template);
            const page = document?.children?.[0];
            return {
                id: item.id,
                nodes: page?.children ?? [],
                title: item.title,
            };
        }
        else {
            throw Error('Invalid Id');
        }
    }
}

class AXPDesignerConnectorImpl extends AXPDesignerConnector {
    constructor() {
        super(...arguments);
        this.workflow = inject(AXPWorkflowService);
        this.entityService = inject(AXPEntityService);
        this.templateEntityService = inject(AXMFormTemplateManagementTemplateEntityService);
        this.categoryEntityDataAccessor = this.entityService
            .withEntity(RootConfig.module.name, `${RootConfig.entities.template.name}Category`)
            .data();
    }
    //#region Save and load Widgets
    async save(id, content) {
        const item = await this.templateEntityService.getOne(id);
        if (item) {
            await this.templateEntityService.updateOne(id, { template: content.json });
            return true;
        }
        else {
            throw Error("Invalid Id");
        }
    }
    async saveAs(content) {
        const result = await this.workflow.execute('create-entity', {
            redirect: false,
            entity: `${RootConfig.module.name}.${RootConfig.entities.template.name}`,
            canCreateNewOne: false,
            data: {
                name: AXPDataGenerator.alphanumeric(10),
                type: AXMFormTemplateTypes.Widget,
                template: content.json,
                categoryId: (await this.categoryEntityDataAccessor.query()).items[0]?.id
            }
        });
        return result.getOutput('result');
    }
    async load(id) {
        const item = await this.templateEntityService.getOne(id);
        if (item) {
            return item.template;
        }
        else {
            throw Error("Invalid Id");
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPDesignerConnectorImpl, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPDesignerConnectorImpl }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPDesignerConnectorImpl, decorators: [{
            type: Injectable
        }] });

const AXMCreateFormTemplateWorkflow = {
    startStepId: 'create-form-template',
    steps: {
        "create-form-template": {
            action: 'start-workflow',
            input: {
                workflow: "create-entity",
                context: {
                    redirect: true,
                    entity: `${RootConfig.module.name}.${RootConfig.entities.template.name}`,
                },
                options: {
                    process: {
                        redirect: false,
                    }
                }
            },
            // nextSteps: [
            //     {
            //         conditions: [{ type: 'SINGLE', expression: 'context.getOutput("result") == true' }],
            //         nextStepId: 'get-template-confirmaton',
            //     },
            // ],
        },
        "get-template-confirmaton": {
            action: 'show-prompt-dialog',
            input: {
                title: 'Confirm Action',
                message: `Would you like to proceed with starting template design?`,
                type: 'primary',
            },
            nextSteps: [
                {
                    conditions: [{ type: 'SINGLE', expression: 'context.getOutput("result") == true' }],
                    nextStepId: 'template-design',
                },
            ],
        },
        "template-design": {
            action: 'open-form-template-designer',
        },
    },
};

const AXMDesignFormTemplateWorkflow = {
    startStepId: 'open',
    steps: {
        "open": {
            action: 'decide',
            nextSteps: [
                {
                    conditions: [{ type: 'SINGLE', expression: '  context.getVariable("embedded") == true' }],
                    nextStepId: 'embedded',
                },
                {
                    conditions: [{ type: 'SINGLE', expression: ' !context.getVariable("embedded")' }],
                    nextStepId: 'form',
                },
            ],
        },
        'embedded': {
            action: 'open-embedded-template-designer',
            nextSteps: [
                {
                    conditions: [{ type: 'SINGLE', expression: '  context.getOutput("result") == true' }],
                    nextStepId: 'save-embedded',
                },
            ],
        },
        'form': {
            action: 'open-form-template-designer',
        },
        'save-embedded': {
            action: 'save-embedded-template-designer',
        },
    },
};

const AXP_TEMPLATE_WIDGET_PROVIDER = new InjectionToken('AXP_TEMPLATE_WIDGET_PROVIDER');
class AXPTemplateWidgetProviderService {
    constructor() {
        this.popupService = inject(AXPopupService);
        this.translate = inject(AXTranslationService);
        this.providers = inject(AXP_TEMPLATE_WIDGET_PROVIDER, { optional: true });
    }
    async items(query) {
        if (Array.isArray(this.providers)) {
            const result = [];
            for (const provider of this.providers) {
                const items = await provider.items(query);
                if (items) {
                    result.push(...items);
                }
            }
            return result;
        }
        else {
            return [];
        }
    }
    async get(id) {
        if (Array.isArray(this.providers)) {
            for (const provider of this.providers) {
                const node = await provider.get(id);
                if (node) {
                    return node;
                }
            }
        }
        return null;
    }
    async chooseTemplate() {
        const com = await import('./acorex-modules-form-template-management-template-picker.component-Zfzq-GCE.mjs').then((c) => c.AXPTemplateWidgetPickerComponent);
        const widgets = await this.items({
            skip: 0,
            take: 100,
            filter: {
                field: 'type.id',
                value: 20,
                operator: {
                    type: 'equal',
                },
            },
        });
        const result = await this.popupService.open(com, {
            title: await this.translate.translateAsync('@form-template-management:designer.components.template-picker.title'),
            size: 'lg',
            closeButton: true,
            data: {
                widgets: sortBy(widgets, (c) => c.title),
            },
        });
        if (result.data) {
            const selected = result.data?.widgets;
            return selected[0];
        }
        return null;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPTemplateWidgetProviderService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPTemplateWidgetProviderService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPTemplateWidgetProviderService, decorators: [{
            type: Injectable,
            args: [{ providedIn: 'root' }]
        }] });

class AXPTemplateWidgetViewComponent extends AXPValueWidgetComponent {
    constructor() {
        super();
        this.metaKey = '__meta__';
        this.templateProvider = inject(AXPTemplateWidgetProviderService);
        this.templateId = computed(() => this.options()['templateId'], ...(ngDevMode ? [{ debugName: "templateId" }] : []));
        this.nodes = signal([], ...(ngDevMode ? [{ debugName: "nodes" }] : []));
        //
        effect(async () => {
            this.nodes.set([]);
            const value = this.getValue();
            const templateId = get(value, `${this.metaKey}.templateId`) ?? this.templateId();
            if (templateId) {
                const item = await this.templateProvider.get(templateId);
                if (item) {
                    this.nodes.set(item.nodes);
                }
            }
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPTemplateWidgetViewComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.19", type: AXPTemplateWidgetViewComponent, isStandalone: true, selector: "axp-template-widget-view", usesInheritance: true, ngImport: i0, template: `
    @for (node of nodes(); track $index) {
      <ng-container axp-widget-renderer [node]="node" [parentNode]="this" [mode]="this.mode"> </ng-container>
    } @empty {
      <span class="ax-underline ax-decoration-dotted  ax-underline-offset-8 ax-text-gray-400">
        {{ '@form-template-management:templates.terms.empty-template' | translate | async }}
      </span>
    }
  `, isInline: true, dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: AXPWidgetCoreModule }, { kind: "directive", type: i1.AXPWidgetRendererDirective, selector: "[axp-widget-renderer]", inputs: ["parentNode", "index", "mode", "node"], outputs: ["onOptionsChanged", "onValueChanged", "onLoad"], exportAs: ["widgetRenderer"] }, { kind: "ngmodule", type: AXTranslationModule }, { kind: "pipe", type: i2.AsyncPipe, name: "async" }, { kind: "pipe", type: i3.AXTranslatorPipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPTemplateWidgetViewComponent, decorators: [{
            type: Component,
            args: [{
                    selector: 'axp-template-widget-view',
                    template: `
    @for (node of nodes(); track $index) {
      <ng-container axp-widget-renderer [node]="node" [parentNode]="this" [mode]="this.mode"> </ng-container>
    } @empty {
      <span class="ax-underline ax-decoration-dotted  ax-underline-offset-8 ax-text-gray-400">
        {{ '@form-template-management:templates.terms.empty-template' | translate | async }}
      </span>
    }
  `,
                    changeDetection: ChangeDetectionStrategy.OnPush,
                    imports: [CommonModule, AXPWidgetCoreModule, AXTranslationModule],
                }]
        }], ctorParameters: () => [] });

var templateWidgetView_component = /*#__PURE__*/Object.freeze({
    __proto__: null,
    AXPTemplateWidgetViewComponent: AXPTemplateWidgetViewComponent
});

const AXP_DESIGNER_TEMPLATE_WIDGET_CHOOSE_MENU = {
    text: 'Choose Template',
    name: 'choose',
    icon: 'fa-solid fa-folder-open',
};
class AXPTemplateWidgetDesignerComponent extends AXPValueWidgetComponent {
    constructor() {
        super();
        this.templateProvider = inject(AXPTemplateWidgetProviderService);
        this.designerService = inject(AXPDesignerService);
        this.templateId = computed(() => this.options()['templateId'], ...(ngDevMode ? [{ debugName: "templateId" }] : []));
        this.nodes = signal([], ...(ngDevMode ? [{ debugName: "nodes" }] : []));
        this.title = signal(null, ...(ngDevMode ? [{ debugName: "title" }] : []));
        //
        effect(async () => {
            this.nodes.set([]);
            if (this.templateId()) {
                const item = await this.templateProvider.get(this.templateId());
                if (item && item.nodes?.length > 0) {
                    this.title.set(item.title);
                    this.nodes.set(item.nodes);
                }
            }
        });
    }
    async handleChooseWidget() {
        const result = await this.templateProvider.chooseTemplate();
        if (result) {
            this.designerService.update({
                mode: 'update',
                values: { options: { templateId: result.id } },
                widget: this.node,
            });
        }
    }
    get __class() {
        const cls = {};
        //
        cls[`ax-w-full`] = true;
        cls[`ax-widget-outline`] = true;
        //
        cls[`ax-block`] = true;
        return cls;
    }
    onContextMenu(context) {
        const items = [AXP_DESIGNER_TEMPLATE_WIDGET_CHOOSE_MENU];
        items[items.length - 1].break = true;
        context.items.unshift(...items);
    }
    async executeCommand(command) {
        switch (command.name) {
            case AXP_DESIGNER_TEMPLATE_WIDGET_CHOOSE_MENU.name:
                await this.handleChooseWidget();
                break;
        }
        return Promise.resolve();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPTemplateWidgetDesignerComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.19", type: AXPTemplateWidgetDesignerComponent, isStandalone: true, selector: "axp-template-widget-designer", host: { properties: { "class": "this.__class" } }, providers: [
            {
                provide: AXPLayoutBaseWidgetComponent,
                useExisting: AXPTemplateWidgetDesignerComponent,
            },
        ], usesInheritance: true, ngImport: i0, template: `
    @if (nodes().length) {
      <div class="ax-relative ax-block ax-w-full ax-pointer-events-none">
        @for (node of nodes(); track $index) {
          <ng-container
            axp-widget-designer-renderer
            [locked]="true"
            [node]="node"
            [parentNode]="this"
            [mode]="this.mode"
          >
          </ng-container>
        }
        <div
          class="ax-absolute ax-top-0 ax-bottom-0 ax-left-0 ax-right-0 ax-bg-blue-400 ax-opacity-30 ax-flex ax-justify-center ax-items-center ax-z-[400]"
        >
          <span class="ax-capitalize ax-font-semibold ax-text-primary-700"> {{ title() }}</span>
        </div>
      </div>
    } @else {
      <axp-designer-add-widget-mini-button
        class="ax-flex-1 ax-self-center ax-place-self-end"
        (onClick)="handleChooseWidget()"
      >
      </axp-designer-add-widget-mini-button>
    }
  `, isInline: true, dependencies: [{ kind: "ngmodule", type: AXPWidgetCoreModule }, { kind: "directive", type: AXPWidgetDesignerRendererDirective, selector: "[axp-widget-designer-renderer]", inputs: ["parentNode", "parentElement", "parentComponent", "index", "locked", "mode", "node"] }, { kind: "component", type: AXPDesignerAddWidgetMiniButtonComponent, selector: "axp-designer-add-widget-mini-button", outputs: ["onClick"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPTemplateWidgetDesignerComponent, decorators: [{
            type: Component,
            args: [{
                    selector: 'axp-template-widget-designer',
                    template: `
    @if (nodes().length) {
      <div class="ax-relative ax-block ax-w-full ax-pointer-events-none">
        @for (node of nodes(); track $index) {
          <ng-container
            axp-widget-designer-renderer
            [locked]="true"
            [node]="node"
            [parentNode]="this"
            [mode]="this.mode"
          >
          </ng-container>
        }
        <div
          class="ax-absolute ax-top-0 ax-bottom-0 ax-left-0 ax-right-0 ax-bg-blue-400 ax-opacity-30 ax-flex ax-justify-center ax-items-center ax-z-[400]"
        >
          <span class="ax-capitalize ax-font-semibold ax-text-primary-700"> {{ title() }}</span>
        </div>
      </div>
    } @else {
      <axp-designer-add-widget-mini-button
        class="ax-flex-1 ax-self-center ax-place-self-end"
        (onClick)="handleChooseWidget()"
      >
      </axp-designer-add-widget-mini-button>
    }
  `,
                    changeDetection: ChangeDetectionStrategy.OnPush,
                    imports: [
                        AXPWidgetCoreModule,
                        AXPWidgetDesignerRendererDirective,
                        AXPDesignerAddWidgetMiniButtonComponent
                    ],
                    providers: [
                        {
                            provide: AXPLayoutBaseWidgetComponent,
                            useExisting: AXPTemplateWidgetDesignerComponent,
                        },
                    ],
                }]
        }], ctorParameters: () => [], propDecorators: { __class: [{
                type: HostBinding,
                args: ['class']
            }] } });

var templateWidgetDesigner_component = /*#__PURE__*/Object.freeze({
    __proto__: null,
    AXPTemplateWidgetDesignerComponent: AXPTemplateWidgetDesignerComponent,
    AXP_DESIGNER_TEMPLATE_WIDGET_CHOOSE_MENU: AXP_DESIGNER_TEMPLATE_WIDGET_CHOOSE_MENU
});

const AXPTemplateWidget = {
    name: 'template',
    title: 'Template',
    type: 'container',
    icon: 'fa-light fa-file-invoice',
    categories: [AXP_WIDGETS_ADVANCE_CATEGORY],
    groups: [AXPWidgetGroupEnum.FormElement],
    designer: {
        canInsert: false,
    },
    properties: [
        AXP_NAME_PROPERTY,
        AXP_DATA_PATH_PROPERTY,
        createStringProperty({
            name: 'options.templateId',
            title: 'Template',
            group: AXP_BEHAVIOR_PROPERTY_GROUP,
            visible: false,
        }),
    ],
    components: {
        view: {
            component: () => Promise.resolve().then(function () { return templateWidgetView_component; }).then((c) => c.AXPTemplateWidgetViewComponent),
        },
        edit: {
            component: () => import('./acorex-modules-form-template-management-template-widget-edit.component-BPLAqfDn.mjs').then((c) => c.AXPTemplateWidgetEditComponent),
        },
        print: {
            component: () => Promise.resolve().then(function () { return templateWidgetView_component; }).then((c) => c.AXPTemplateWidgetViewComponent),
        },
        designer: {
            component: () => Promise.resolve().then(function () { return templateWidgetDesigner_component; }).then((c) => c.AXPTemplateWidgetDesignerComponent),
        },
    },
};

class AXPTemplateDesignerWidgetViewComponent extends AXPValueWidgetComponent {
    constructor() {
        super(...arguments);
        this.workflow = inject(AXPWorkflowService);
        this.embedded = computed(() => this.options()['embedded'] ?? false, ...(ngDevMode ? [{ debugName: "embedded" }] : []));
    }
    async handleClick() {
        if (this.embedded()) {
            const context = await this.workflow.execute('design-form-template', { embedded: true, content: this.getValue() });
            const content = context.getVariable('content');
            this.setValue(content);
        }
        else {
            const id = this.extractValue('id');
            const context = await this.workflow.execute('design-form-template', { id });
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPTemplateDesignerWidgetViewComponent, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.19", type: AXPTemplateDesignerWidgetViewComponent, isStandalone: true, selector: "ng-component", usesInheritance: true, ngImport: i0, template: `
    <span
      class="ax-underline ax-decoration-dotted  ax-underline-offset-8 hover:ax-text-primary-500 ax-cursor-pointer"
      (click)="handleClick()"
    >
      {{ '@form-template-management:designer.terms.edit-template' | translate | async }}
    </span>
  `, isInline: true, dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: AXTranslationModule }, { kind: "pipe", type: i2.AsyncPipe, name: "async" }, { kind: "pipe", type: i3.AXTranslatorPipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPTemplateDesignerWidgetViewComponent, decorators: [{
            type: Component,
            args: [{
                    template: `
    <span
      class="ax-underline ax-decoration-dotted  ax-underline-offset-8 hover:ax-text-primary-500 ax-cursor-pointer"
      (click)="handleClick()"
    >
      {{ '@form-template-management:designer.terms.edit-template' | translate | async }}
    </span>
  `,
                    changeDetection: ChangeDetectionStrategy.OnPush,
                    imports: [CommonModule, AXTranslationModule]
                }]
        }] });

var templateDesignerWidgetView_component = /*#__PURE__*/Object.freeze({
    __proto__: null,
    AXPTemplateDesignerWidgetViewComponent: AXPTemplateDesignerWidgetViewComponent
});

const AXPTemplateDesignerWidget = {
    name: "template-designer",
    title: "Template Designer",
    icon: "fa-solid fa-square",
    type: 'editor',
    categories: AXP_WIDGETS_LAYOUT_CATEGORY,
    properties: [
        AXP_NAME_PROPERTY,
        AXP_DATA_PATH_PROPERTY,
    ],
    components: {
        view: {
            component: () => Promise.resolve().then(function () { return templateDesignerWidgetView_component; }).then((c) => c.AXPTemplateDesignerWidgetViewComponent),
        },
        edit: {
            component: () => Promise.resolve().then(function () { return templateDesignerWidgetView_component; }).then((c) => c.AXPTemplateDesignerWidgetViewComponent),
        }
    }
};

/**
 * Show Form Activity - Displays a form dialog using Layout Builder.
 *
 * This activity creates a form dialog with fields defined using the Layout Builder API.
 * It waits for user interaction (submit/cancel) and returns the form data and action outcome.
 *
 * Usage in Workflow:
 * ```json
 * {
 *   "type": "workflow-activity:show-form",
 *   "properties": {
 *     "title": "Login Form",
 *     "formDefinition": {
 *       "fields": [
 *         {
 *           "label": "Username",
 *           "type": "text-editor",
 *           "path": "username",
 *           "required": true
 *         },
 *         {
 *           "label": "Password",
 *           "type": "password-editor",
 *           "path": "password",
 *           "required": true
 *         }
 *       ]
 *     },
 *     "actions": ["submit", "cancel"],
 *     "context": {}
 *   }
 * }
 * ```
 */
// export class ShowForm implements AXPActivity<{
//   type: "workflow-activity:show-form";
//   /**
//    * Dialog title
//    */
//   title: string;
//   /**
//    * Form definition - can be:
//    * - JSON object with fields array
//    * - Widget node definition
//    */
//   formDefinition: any;
//   /**
//    * Initial form context/data
//    */
//   context?: Record<string, any>;
//   /**
//    * Dialog size
//    */
//   size?: AXPopupSizeType;
//   /**
//    * Show close button
//    */
//   closeButton?: boolean;
//   /**
//    * Actions to show (submit, cancel, or custom)
//    */
//   actions?: {
//     submit?: string; // Submit button text
//     cancel?: string; // Cancel button text
//     custom?: Array<{
//       title: string;
//       icon?: string;
//       color?: string;
//       command: string;
//     }>;
//   };
// }, {
//   formData: Record<string, any>;
//   action: string;
//   cancelled: boolean;
// }> {
//   private readonly layoutBuilderService = inject(AXPLayoutBuilderService);
//   constructor() {
//     super('workflow-activity:show-form', 'Show Form');
//   }
//   async execute(input: {
//     title: string;
//     formDefinition: any;
//     context?: Record<string, any>;
//     size?: AXPopupSizeType;
//     closeButton?: boolean;
//     actions?: {
//       submit?: string;
//       cancel?: string;
//       custom?: Array<{
//         title: string;
//         icon?: string;
//         color?: string;
//         command: string;
//       }>;
//     };
//   }) {
//     const {
//       title,
//       formDefinition,
//       context = {},
//       size = 'md',
//       closeButton = false,
//       actions = {
//         submit: '@general:actions.submit.title',
//         cancel: '@general:actions.cancel.title'
//       }
//     } = input;
//     try {
//       // Create dialog with form
//       const dialogRef = await this.layoutBuilderService
//         .create()
//         .dialog((dialog) => {
//           dialog
//             .setTitle(title)
//             .setSize(size)
//             .setCloseButton(closeButton)
//             .setContext(context)
//             .content((content) => {
//               // Build form fields from definition
//               this.buildFormFields(content, formDefinition);
//             })
//             .setActions((actionBuilder) => {
//               // Add cancel action
//               if (actions.cancel !== undefined && actions.cancel !== null) {
//                 actionBuilder.cancel(actions.cancel);
//               }
//               // Add submit action
//               if (actions.submit !== undefined && actions.submit !== null) {
//                 actionBuilder.submit(actions.submit);
//               }
//               // Add custom actions
//               if (actions.custom && Array.isArray(actions.custom)) {
//                 for (const customAction of actions.custom) {
//                   actionBuilder.custom({
//                     title: customAction.title,
//                     icon: customAction.icon || 'fa-circle',
//                     color: customAction.color || 'primary',
//                     command: { name: customAction.command }
//                   });
//                 }
//               }
//             });
//         })
//         .show();
//       // Wait for user interaction
//       const action = dialogRef.action() || 'cancel';
//       const formData = dialogRef.context() || {};
//       const cancelled = action === 'cancel';
//       // Map action to outcome
//       const outcome = cancelled ? 'Cancelled' : (action === 'submit' ? 'Submitted' : action);
//       return this.createResult(
//         {
//           formData,
//           action,
//           cancelled
//         },
//         outcome
//       );
//     } catch (error: any) {
//       console.error('[ShowForm] Error displaying form:', error);
//       return {
//         success: false,
//         error: {
//           message: error instanceof Error ? error.message : 'Failed to display form dialog',
//         },
//         result: {
//           output: {
//             formData: {},
//             action: 'error',
//             cancelled: true,
//           },
//           outcomes: {
//             Failed: true,
//           },
//         },
//       };
//     }
//   }
//   /**
//    * Build form fields from definition
//    */
//   private buildFormFields(contentBuilder: any, formDefinition: any): void {
//     // Check if formDefinition is a widget node (already built)
//     if (formDefinition?.type && formDefinition?.children) {
//       // Already a widget node - use it directly
//       const flexBuilder = this.layoutBuilderService.create().flex((flex) => {
//         // Convert widget node to form fields
//         this.convertWidgetNodeToFields(flex, formDefinition);
//       });
//       // Note: This is a simplified approach - in production, you'd need to properly integrate
//       return;
//     }
//     // Handle JSON form definition
//     if (formDefinition?.fields && Array.isArray(formDefinition.fields)) {
//       // Simple fields array format
//       for (const field of formDefinition.fields) {
//         this.addFormField(contentBuilder, field);
//       }
//     } else if (formDefinition?.groups && Array.isArray(formDefinition.groups)) {
//       // Groups format (like dynamic form designer)
//       for (const group of formDefinition.groups) {
//         if (group.fields && Array.isArray(group.fields)) {
//           for (const field of group.fields) {
//             this.addFormField(contentBuilder, field);
//           }
//         }
//       }
//     } else {
//       // Assume it's a widget node structure
//       this.convertWidgetNodeToFields(contentBuilder, formDefinition);
//     }
//   }
//   /**
//    * Add a single form field
//    */
//   private addFormField(contentBuilder: any, field: any): void {
//     const {
//       label,
//       type = 'text-editor',
//       path,
//       name,
//       options = {},
//       required = false,
//       readonly = false,
//       disabled = false,
//       visible = true,
//       defaultValue
//     } = field;
//     if (!label || !path) {
//       console.warn('[ShowForm] Skipping field without label or path:', field);
//       return;
//     }
//     // Create form field
//     contentBuilder.formField(label, (formField: any) => {
//       // Set field properties
//       if (readonly) {
//         formField.readonly(true);
//       }
//       if (disabled) {
//         formField.disabled(true);
//       }
//       if (!visible) {
//         formField.visible(false);
//       }
//       if (defaultValue !== undefined) {
//         // Set default value in options
//         const fieldOptions = { ...options, defaultValue };
//         this.addWidgetToFormField(formField, type, path, name || path, fieldOptions);
//       } else {
//         this.addWidgetToFormField(formField, type, path, name || path, options);
//       }
//     });
//   }
//   /**
//    * Add widget to form field based on type
//    */
//   private addWidgetToFormField(formField: any, type: string, path: string, name: string, options: any): void {
//     switch (type) {
//       case 'text-editor':
//       case 'textbox':
//         formField.textBox({ path, name, ...options });
//         break;
//       case 'large-text-editor':
//       case 'large-textbox':
//         formField.largeTextBox({ path, name, ...options });
//         break;
//       case 'rich-text-editor':
//       case 'richtext':
//         formField.richText({ path, name, ...options });
//         break;
//       case 'password-editor':
//       case 'password':
//         formField.passwordBox({ path, name, ...options });
//         break;
//       case 'number-editor':
//       case 'numberbox':
//         formField.numberBox({ path, name, ...options });
//         break;
//       case 'select-editor':
//       case 'selectbox':
//         formField.selectBox({ path, name, ...options });
//         break;
//       case 'lookup-editor':
//       case 'lookup':
//         formField.lookupBox({ path, name, ...options });
//         break;
//       case 'selection-list-editor':
//       case 'selection-list':
//         formField.selectionList({ path, name, ...options });
//         break;
//       case 'date-time-editor':
//       case 'datetime':
//         formField.dateTimeBox({ path, name, ...options });
//         break;
//       case 'toggle-editor':
//       case 'toggle':
//         formField.toggleSwitch({ path, name, ...options });
//         break;
//       case 'color-editor':
//       case 'color':
//         formField.colorBox({ path, name, ...options });
//         break;
//       default:
//         // Custom widget type
//         formField.customWidget(type, { path, name, ...options });
//         break;
//     }
//   }
//   /**
//    * Convert widget node to form fields (recursive)
//    */
//   private convertWidgetNodeToFields(contentBuilder: any, node: any): void {
//     if (!node) return;
//     // If it's a form-field node, extract it
//     if (node.type === 'form-field') {
//       const label = node.options?.label || node.name || 'Field';
//       const widget = node.children?.[0];
//       if (widget) {
//         contentBuilder.formField(label, (formField: any) => {
//           // Map widget properties
//           if (node.options?.readonly) {
//             formField.readonly(true);
//           }
//           if (node.options?.disabled) {
//             formField.disabled(true);
//           }
//           if (node.options?.visible === false) {
//             formField.visible(false);
//           }
//           // Add widget based on type
//           const path = widget.path || widget.name || label.toLowerCase().replace(/\s+/g, '_');
//           const name = widget.name || path;
//           const options = { ...widget.options };
//           this.addWidgetToFormField(formField, widget.type, path, name, options);
//         });
//       }
//     } else if (node.children && Array.isArray(node.children)) {
//       // Recursively process children
//       for (const child of node.children) {
//         this.convertWidgetNodeToFields(contentBuilder, child);
//       }
//     }
//   }
// }

class AXPFormTemplateViewerConnector {
}
class AXPFormTemplateViewerConnectorImpl extends AXPFormTemplateViewerConnector {
    constructor() {
        super(...arguments);
        this.templateEntityService = inject(AXMFormTemplateManagementTemplateEntityService);
    }
    //#region Save and load Widgets
    async submit(id, context, metadeta) {
        return Promise.resolve(true);
    }
    async load(id) {
        const item = await this.templateEntityService.getOne(id);
        if (item) {
            return item.template;
        }
        else {
            throw Error('Invalid Id');
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPFormTemplateViewerConnectorImpl, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPFormTemplateViewerConnectorImpl }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXPFormTemplateViewerConnectorImpl, decorators: [{
            type: Injectable
        }] });

class AXMOpenFormTemplateViewerAction extends AXPWorkflowAction {
    constructor() {
        super(...arguments);
        //#region ----   Services & Dependencies   ----
        this.templateViewerService = inject(AXPTemplateViewerService);
        this.connector = inject(AXPFormTemplateViewerConnector);
    }
    //#endregion
    //#region ----   Workflow Execution   ----
    async execute(context) {
        const { id, template } = context.getVariable('data');
        const metadata = context.getVariable('metadata');
        let templateData;
        if (id) {
            // Load template from database using connector
            templateData = await this.connector.load(id) || '';
        }
        else if (template) {
            // Use provided template string
            templateData = template;
        }
        else {
            throw new Error('Either template ID or template data must be provided');
        }
        const result = await this.templateViewerService.showTemplate({
            template: templateData,
            title: 'Form Template Viewer',
            context: {},
            metadata,
            readOnly: false,
            showActions: true
        });
        context.setOutput('result', !result.cancelled);
        if (!result.cancelled && result.context) {
            context.setOutput('form-context', result.context);
            // If we have an ID, submit the form data using the connector
            if (id) {
                await this.connector.submit(id, result.context, metadata);
            }
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMOpenFormTemplateViewerAction, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMOpenFormTemplateViewerAction }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMOpenFormTemplateViewerAction, decorators: [{
            type: Injectable
        }] });
//#region ----   Workflow Definition   ----
const AXMOpenFormTemplateViewerWorkflow = {
    startStepId: 'open-form',
    steps: {
        "open-form": {
            action: 'open-form-template-viewer',
        },
    },
};

class AXMOpenFormTemplateDesignerAction extends AXPWorkflowAction {
    constructor() {
        super(...arguments);
        this.navigation = inject(AXPWorkflowNavigateAction);
    }
    async execute(context) {
        const id = context.getVariable('id') ?? context.getVariable('data.id') ?? AXPDataGenerator.uuid();
        context.setVariable('payload', {
            commands: `forms/designer?id=${id}`,
            target: 'blank'
        });
        await this.navigation.execute(context);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMOpenFormTemplateDesignerAction, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMOpenFormTemplateDesignerAction }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMOpenFormTemplateDesignerAction, decorators: [{
            type: Injectable
        }] });
class AXMOpenEmbeddedTemplateDesignerAction extends AXPWorkflowAction {
    constructor() {
        super(...arguments);
        this.navigation = inject(AXPWorkflowNavigateAction);
        this.broadcastService = inject(AXPBroadcastEventService);
    }
    async execute(context) {
        const id = context.getVariable('id') ?? context.getVariable('data.id') ?? AXPDataGenerator.uuid();
        context.setVariable('payload', {
            commands: `forms/designer?id=${id}&strategy=Broadcast`,
            target: 'blank'
        });
        await this.navigation.execute(context);
        return new Promise((resolve, reject) => {
            this.broadcastService.listen(AXPDesignerMessageKeys.RequestFormContent).subscribe(async (event) => {
                if (event.requestId && event.data.formId == id) {
                    const content = context.getVariable('content') ?? null;
                    this.broadcastService.respondToRequest(event.requestId, content);
                    context.setOutput("result", true);
                    resolve();
                }
                else {
                    context.setOutput("result", false);
                    reject('No valid requestId found in the event.');
                }
            });
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMOpenEmbeddedTemplateDesignerAction, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMOpenEmbeddedTemplateDesignerAction }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMOpenEmbeddedTemplateDesignerAction, decorators: [{
            type: Injectable
        }] });
class AXMSaveEmbeddedTemplateDesignerAction extends AXPWorkflowAction {
    constructor() {
        super(...arguments);
        this.broadcastService = inject(AXPBroadcastEventService);
    }
    async execute(context) {
        return new Promise((resolve, reject) => {
            this.broadcastService.listen(AXPDesignerMessageKeys.SaveForm).subscribe(async (event) => {
                if (event.data.success) {
                    this.broadcastService.respondToRequest(event.requestId, { success: true });
                    context.setVariable('content', event.data.content);
                    context.setOutput('result', true);
                }
                else {
                    context.setOutput('result', false);
                }
                resolve();
            });
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMSaveEmbeddedTemplateDesignerAction, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMSaveEmbeddedTemplateDesignerAction }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMSaveEmbeddedTemplateDesignerAction, decorators: [{
            type: Injectable
        }] });

const AXM_FORM_TEMPLATE_CODE_IDENTIFIER_RULE = {
    id: 'form-template',
    title: 'Form Template Code',
    entity: RootConfig.entities.template.source,
    pattern: 'FT-{date:YYYYMMDD}-{seq:4}',
    enabled: true,
    priority: 1,
    scopeConfig: { byTenant: false, period: 'monthly', minValue: 0, blockSize: 0 },
};

function routesFacory() {
    const routes = [
        {
            path: 'forms',
            children: [
                {
                    path: 'designer',
                    loadComponent: () => import('./acorex-modules-form-template-management-designer.page-C7EU83yi.mjs').then((c) => c.AXMFormTemplateManagementModuleDesignerPage),
                },
                {
                    path: 'preview',
                    loadComponent: () => import('@acorex/platform/layout/designer').then((c) => c.AXPLayoutDesignerPreviewComponent),
                },
                {
                    path: 'viewer',
                    loadComponent: () => import('@acorex/platform/layout/designer').then((c) => c.AXPLayoutDesignerPreviewViewerComponent),
                },
            ],
        },
    ];
    return routes;
}
class AXMFormTemplateManagementModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementModule, imports: [AXPWidgetsModule,
            AXMFormTemplateManagementTemplateEntityModule, i1.AXPWidgetCoreModule, i2$1.AXPWorkflowModule] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementModule, providers: [
            // Module-specific providers (not part of manifest system)
            {
                provide: ROUTES,
                multi: true,
                useFactory: routesFacory,
            },
            {
                provide: AXPDesignerConnector,
                useClass: AXPDesignerConnectorImpl,
            },
            {
                provide: AXPFormTemplateViewerConnector,
                useClass: AXPFormTemplateViewerConnectorImpl,
            },
            {
                provide: AXP_TEMPLATE_WIDGET_PROVIDER,
                useClass: AXPTemplateWidgetProviderImpl,
                multi: true,
            },
            {
                provide: AXP_IDENTIFIER_RULES,
                multi: true,
                useValue: AXM_FORM_TEMPLATE_CODE_IDENTIFIER_RULE,
            },
            // Register ShowForm activity as workflow command
            // provideCommandSetups([
            //   {
            //     key: 'workflow-activity:show-form',
            //     command: () => import('./features/activities/show-form.activity').then(m => m.ShowForm),
            //   },
            // ]),
            {
                provide: AXP_MODULE_MANIFEST_PROVIDER,
                useValue: FormTemplateManagementManifest,
                multi: true,
            },
            // Provider references (now using tokens)
            {
                provide: AXP_PERMISSION_DEFINITION_PROVIDER,
                useClass: AXMPermissionDefinitionProvider,
                multi: true,
            },
            {
                provide: AXP_MENU_PROVIDER,
                useClass: AXMMenuProvider,
                multi: true,
            },
            {
                provide: AXP_ENTITY_DEFINITION_LOADER,
                useClass: AXMEntityProvider,
                multi: true,
            },
            {
                provide: AXP_SETTING_DEFINITION_PROVIDER,
                useClass: AXMSettingProvider,
                multi: true,
            },
            {
                provide: AXP_SEARCH_PROVIDER,
                useClass: AXMSearchCommandProvider,
                multi: true,
            },
        ], imports: [AXPWidgetsModule,
            AXMFormTemplateManagementTemplateEntityModule,
            AXPWidgetCoreModule.forChild({
                widgets: [AXPTemplateDesignerWidget, AXPTemplateWidget],
            }),
            AXPWorkflowModule.forChild({
                actions: {
                    'open-form-template-viewer': AXMOpenFormTemplateViewerAction,
                    //
                    'open-form-template-designer': AXMOpenFormTemplateDesignerAction,
                    'open-embedded-template-designer': AXMOpenEmbeddedTemplateDesignerAction,
                    //
                    'save-embedded-template-designer': AXMSaveEmbeddedTemplateDesignerAction
                },
                workflows: {
                    'create-form-template': AXMCreateFormTemplateWorkflow,
                    'design-form-template': AXMDesignFormTemplateWorkflow,
                    'open-form-template': AXMOpenFormTemplateViewerWorkflow
                },
            })] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMFormTemplateManagementModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        AXPWidgetsModule,
                        AXMFormTemplateManagementTemplateEntityModule,
                        AXPWidgetCoreModule.forChild({
                            widgets: [AXPTemplateDesignerWidget, AXPTemplateWidget],
                        }),
                        AXPWorkflowModule.forChild({
                            actions: {
                                'open-form-template-viewer': AXMOpenFormTemplateViewerAction,
                                //
                                'open-form-template-designer': AXMOpenFormTemplateDesignerAction,
                                'open-embedded-template-designer': AXMOpenEmbeddedTemplateDesignerAction,
                                //
                                'save-embedded-template-designer': AXMSaveEmbeddedTemplateDesignerAction
                            },
                            workflows: {
                                'create-form-template': AXMCreateFormTemplateWorkflow,
                                'design-form-template': AXMDesignFormTemplateWorkflow,
                                'open-form-template': AXMOpenFormTemplateViewerWorkflow
                            },
                        }),
                    ],
                    exports: [],
                    declarations: [],
                    providers: [
                        // Module-specific providers (not part of manifest system)
                        {
                            provide: ROUTES,
                            multi: true,
                            useFactory: routesFacory,
                        },
                        {
                            provide: AXPDesignerConnector,
                            useClass: AXPDesignerConnectorImpl,
                        },
                        {
                            provide: AXPFormTemplateViewerConnector,
                            useClass: AXPFormTemplateViewerConnectorImpl,
                        },
                        {
                            provide: AXP_TEMPLATE_WIDGET_PROVIDER,
                            useClass: AXPTemplateWidgetProviderImpl,
                            multi: true,
                        },
                        {
                            provide: AXP_IDENTIFIER_RULES,
                            multi: true,
                            useValue: AXM_FORM_TEMPLATE_CODE_IDENTIFIER_RULE,
                        },
                        // Register ShowForm activity as workflow command
                        // provideCommandSetups([
                        //   {
                        //     key: 'workflow-activity:show-form',
                        //     command: () => import('./features/activities/show-form.activity').then(m => m.ShowForm),
                        //   },
                        // ]),
                        {
                            provide: AXP_MODULE_MANIFEST_PROVIDER,
                            useValue: FormTemplateManagementManifest,
                            multi: true,
                        },
                        // Provider references (now using tokens)
                        {
                            provide: AXP_PERMISSION_DEFINITION_PROVIDER,
                            useClass: AXMPermissionDefinitionProvider,
                            multi: true,
                        },
                        {
                            provide: AXP_MENU_PROVIDER,
                            useClass: AXMMenuProvider,
                            multi: true,
                        },
                        {
                            provide: AXP_ENTITY_DEFINITION_LOADER,
                            useClass: AXMEntityProvider,
                            multi: true,
                        },
                        {
                            provide: AXP_SETTING_DEFINITION_PROVIDER,
                            useClass: AXMSettingProvider,
                            multi: true,
                        },
                        {
                            provide: AXP_SEARCH_PROVIDER,
                            useClass: AXMSearchCommandProvider,
                            multi: true,
                        },
                    ],
                }]
        }] });

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

export { AXMCreateFormTemplateWorkflow, AXMDesignFormTemplateWorkflow, AXMFormTemplateManagementModule, AXMFormTemplateManagementTemplateEntityModule, AXMFormTemplateManagementTemplateEntityService, AXMFormTemplateManagementTemplateEntityServiceImpl, AXMFormTemplateTypes, AXPDesignerConnectorImpl, AXPFormTemplateManagementMenuKeys, AXPFormTemplateManagementPermissionKeys, AXPTemplateDesignerWidget, AXPTemplateDesignerWidgetViewComponent, AXPTemplateWidget, AXPTemplateWidgetDesignerComponent, AXPTemplateWidgetProviderService, AXPTemplateWidgetViewComponent, AXP_DESIGNER_TEMPLATE_WIDGET_CHOOSE_MENU, AXP_TEMPLATE_WIDGET_PROVIDER, RootConfig };
//# sourceMappingURL=acorex-modules-form-template-management.mjs.map
