import * as i0 from '@angular/core';
import { Component, EventEmitter, Output } from '@angular/core';
import { gettext } from '@c8y/ngx-components/gettext';
import { camelCase } from 'lodash-es';
import { CellRendererContext, BaseColumn, getBasicInputArrayFormFieldConfig, alertOnError, AssetPropertyService, BottomDrawerRef, AlertService, DataGridComponent, C8yTranslatePipe } from './c8y-ngx-components.mjs';

class IdentifierCellRendererComponent {
    constructor(context) {
        this.context = context;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: IdentifierCellRendererComponent, deps: [{ token: CellRendererContext }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.19", type: IdentifierCellRendererComponent, isStandalone: true, selector: "c8y-identifier-cell-renderer", ngImport: i0, template: ` {{ context.item.id }} `, isInline: true }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: IdentifierCellRendererComponent, decorators: [{
            type: Component,
            args: [{
                    template: ` {{ context.item.id }} `,
                    selector: 'c8y-identifier-cell-renderer',
                    standalone: true
                }]
        }], ctorParameters: () => [{ type: CellRendererContext }] });

class IdentifierGridColumn extends BaseColumn {
    constructor(initialColumnConfig) {
        super(initialColumnConfig);
        this.name = 'key';
        this.header = gettext('Key');
        this.cellRendererComponent = IdentifierCellRendererComponent;
        this.filterable = true;
        this.filteringConfig = {
            fields: getBasicInputArrayFormFieldConfig({
                key: 'identifiers',
                label: gettext('Show items with identifier'),
                addText: gettext('Add next`identifier`'),
                placeholder: 'c8y_Position'
            }),
            getFilter(_model) {
                return _model;
            }
        };
        this.sortable = false;
    }
}

class TagsCellRendererComponent {
    constructor(context) {
        this.context = context;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: TagsCellRendererComponent, deps: [{ token: CellRendererContext }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.19", type: TagsCellRendererComponent, isStandalone: true, selector: "c8y-tags-cell-renderer", ngImport: i0, template: ` {{ context.item.tags }} `, isInline: true }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: TagsCellRendererComponent, decorators: [{
            type: Component,
            args: [{
                    template: ` {{ context.item.tags }} `,
                    selector: 'c8y-tags-cell-renderer',
                    standalone: true
                }]
        }], ctorParameters: () => [{ type: CellRendererContext }] });

class TagsGridColumn extends BaseColumn {
    constructor(initialColumnConfig) {
        super(initialColumnConfig);
        this.name = 'tags';
        this.header = gettext('Tags');
        this.cellRendererComponent = TagsCellRendererComponent;
        this.filterable = true;
        this.filteringConfig = {
            fields: getBasicInputArrayFormFieldConfig({
                key: 'tags',
                label: gettext('Show items with tags'),
                addText: gettext('Add next`tag`'),
                placeholder: 'tag1'
            }),
            getFilter(_model) {
                return _model;
            }
        };
        this.sortable = false;
    }
}

class TitleCellRendererComponent {
    constructor(context) {
        this.context = context;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: TitleCellRendererComponent, deps: [{ token: CellRendererContext }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.19", type: TitleCellRendererComponent, isStandalone: true, selector: "c8y-title-cell-renderer", ngImport: i0, template: ` {{ context.item.title }} `, isInline: true }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: TitleCellRendererComponent, decorators: [{
            type: Component,
            args: [{
                    template: ` {{ context.item.title }} `,
                    selector: 'c8y-title-cell-renderer',
                    standalone: true
                }]
        }], ctorParameters: () => [{ type: CellRendererContext }] });

class TitleGridColumn extends BaseColumn {
    constructor(initialColumnConfig) {
        super(initialColumnConfig);
        this.name = 'title';
        this.header = gettext('Title');
        this.cellRendererComponent = TitleCellRendererComponent;
        this.filterable = true;
        this.filteringConfig = {
            fields: getBasicInputArrayFormFieldConfig({
                key: 'titles',
                label: gettext('Show items with title'),
                addText: gettext('Add next`title`'),
                placeholder: 'location'
            }),
            getFilter(_model) {
                return _model;
            }
        };
        this.sortable = false;
    }
}

const CHILD_PAGE_SIZE = 5;
const ROOT_PAGE_SIZE = 25;
class AssetPropertyGridComponent {
    constructor(service, bottomDrawerRef, alertService) {
        this.service = service;
        this.bottomDrawerRef = bottomDrawerRef;
        this.alertService = alertService;
        this.columns = [
            new TitleGridColumn(),
            new IdentifierGridColumn(),
            new TagsGridColumn(),
            {
                name: 'description',
                header: gettext('Description'),
                path: 'description',
                filterable: false,
                sortable: false
            },
            {
                name: 'dataType',
                header: gettext('Data Type'),
                path: 'type',
                filterable: false,
                sortable: false
            }
        ];
        this.pagination = { pageSize: ROOT_PAGE_SIZE, currentPage: 1 };
        this.childNodePagination = { pageSize: CHILD_PAGE_SIZE, currentPage: 1 };
        this.serverSideDataCallback = this.onDataSourceModifier.bind(this);
        this.loadError = null;
        this.headerActionControls = [];
        this.displayOptions = {
            bordered: false,
            striped: true,
            filter: true,
            gridHeader: true,
            hover: true
        };
        this.onAddCustomColumn = new EventEmitter();
    }
    async onDataSourceModifier(dataSourceModifier) {
        const { columns, pagination, parentRow } = dataSourceModifier;
        if (parentRow) {
            return this.buildChildGridData(parentRow);
        }
        const { res, data = [], paging } = await alertOnError(this.service.list(this.buildFilter(columns, pagination))).catch(() => {
            this.loadError = gettext('Unable to load asset properties. Please try again later.');
            return {
                res: null,
                data: [],
                paging: null,
                filteredSize: 0,
                size: 0
            };
        });
        const treeNodes = data.map(d => this.toTreeNode(d));
        return {
            res,
            data: treeNodes,
            paging,
            filteredSize: paging?.totalElements,
            size: paging?.totalElements
        };
    }
    async selectItem(identifiers) {
        if (this.bottomDrawerRef) {
            this.bottomDrawerRef.close();
        }
        this.addColumn(identifiers[0]);
    }
    async addColumn(path) {
        const [parentId, childKey] = path.split('.');
        try {
            const def = await this.service.getByIdentifier(parentId);
            const childSchema = def.jsonSchema?.properties?.[childKey];
            const header = childSchema?.title || childKey || def.jsonSchema?.title;
            this.onAddCustomColumn.emit({
                name: camelCase(path),
                header,
                path,
                type: 'property',
                custom: true,
                visible: true
            });
        }
        catch (err) {
            this.alertService.addServerFailure(err);
        }
    }
    close() {
        this.bottomDrawerRef?.close();
    }
    buildChildGridData(parentRow) {
        const children = parentRow.children ?? [];
        const currentPage = parentRow.pagination?.currentPage ?? 1;
        const start = (currentPage - 1) * CHILD_PAGE_SIZE;
        const data = children.slice(start, start + CHILD_PAGE_SIZE);
        const totalPages = Math.ceil(children.length / CHILD_PAGE_SIZE);
        return {
            data,
            filteredSize: children.length,
            size: children.length,
            paging: {
                currentPage,
                pageSize: CHILD_PAGE_SIZE,
                totalPages,
                totalElements: children.length,
                nextPage: currentPage < totalPages ? currentPage + 1 : null,
                prevPage: currentPage > 1 ? currentPage - 1 : null
            },
            parentRow
        };
    }
    buildFilter(columns, pagination) {
        const predicates = columns
            .filter(column => column.filterable && column.externalFilterQuery)
            .reduce((acc, column) => ({ ...acc, ...column.externalFilterQuery }), {});
        return { currentPage: pagination.currentPage, pageSize: pagination.pageSize, ...predicates };
    }
    toTreeNode({ identifier, jsonSchema = {}, tags }) {
        const { title, description, type, properties } = jsonSchema;
        return {
            id: identifier,
            title: title ?? identifier,
            description,
            type,
            tags,
            children: this.mapSchema(properties, identifier),
            hasChildren: !!properties
        };
    }
    mapSchema(props, base = '') {
        if (!props)
            return [];
        return Object.entries(props).map(([key, schema]) => {
            const id = base ? `${base}.${key}` : key;
            const children = this.mapSchema(schema.properties, id);
            return {
                id,
                title: schema.title ?? key,
                description: schema.description,
                type: schema.type,
                children,
                hasChildren: children.length > 0
            };
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AssetPropertyGridComponent, deps: [{ token: AssetPropertyService }, { token: BottomDrawerRef }, { token: AlertService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.19", type: AssetPropertyGridComponent, isStandalone: true, selector: "c8y-asset-property-grid", outputs: { onAddCustomColumn: "onAddCustomColumn" }, host: { classAttribute: "d-contents" }, ngImport: i0, template: "<div class=\"card-block flex-no-shrink separator-bottom col-xs-12 large-padding p-t-24 p-b-24\">\n  <div\n    class=\"h4 text-center text-medium\"\n    id=\"drawerTitle\"\n    translate\n  >\n    Add custom column\n  </div>\n</div>\n<c8y-data-grid\n  class=\"min-height-0 flex-grow d-col\"\n  [title]=\"'Asset properties' | translate\"\n  [loadMoreItemsLabel]=\"'Load more asset properties' | translate\"\n  [loadingItemsLabel]=\"'Loading asset properties\u2026' | translate\"\n  [displayOptions]=\"displayOptions\"\n  [headerActionControls]=\"headerActionControls\"\n  [columns]=\"columns\"\n  [treeGrid]=\"true\"\n  [childNodePagination]=\"childNodePagination\"\n  parentNodeLabelProperty=\"title\"\n  [pagination]=\"pagination\"\n  [serverSideDataCallback]=\"serverSideDataCallback\"\n  [selectable]=\"true\"\n  [singleSelection]=\"true\"\n  (itemsSelect)=\"selectItem($event)\"\n></c8y-data-grid>\n<div class=\"card-footer p-24 separator text-center\">\n  <button\n    class=\"btn btn-default\"\n    type=\"button\"\n    (click)=\"close()\"\n  >\n    {{ ' Cancel' | translate }}\n  </button>\n</div>\n", dependencies: [{ kind: "component", type: DataGridComponent, selector: "c8y-data-grid", inputs: ["title", "loadMoreItemsLabel", "loadingItemsLabel", "showSearch", "refresh", "loading", "columns", "rows", "pagination", "childNodePagination", "infiniteScroll", "serverSideDataCallback", "selectable", "singleSelection", "selectionPrimaryKey", "displayOptions", "actionControls", "bulkActionControls", "headerActionControls", "searchText", "configureColumnsEnabled", "showCounterWarning", "activeClassName", "expandableRows", "treeGrid", "hideReload", "childNodesProperty", "parentNodeLabelProperty"], outputs: ["rowMouseOver", "rowMouseLeave", "rowClick", "onConfigChange", "onBeforeFilter", "onBeforeSearch", "onFilter", "itemsSelect", "onReload", "onAddCustomColumn", "onRemoveCustomColumn", "onColumnFilterReset", "onSort", "onPageSizeChange", "onColumnReordered", "onColumnVisibilityChange"] }, { kind: "pipe", type: C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AssetPropertyGridComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-asset-property-grid', host: { class: 'd-contents' }, standalone: true, imports: [
                        C8yTranslatePipe,
                        DataGridComponent,
                        IdentifierCellRendererComponent,
                        TitleCellRendererComponent,
                        TagsCellRendererComponent
                    ], template: "<div class=\"card-block flex-no-shrink separator-bottom col-xs-12 large-padding p-t-24 p-b-24\">\n  <div\n    class=\"h4 text-center text-medium\"\n    id=\"drawerTitle\"\n    translate\n  >\n    Add custom column\n  </div>\n</div>\n<c8y-data-grid\n  class=\"min-height-0 flex-grow d-col\"\n  [title]=\"'Asset properties' | translate\"\n  [loadMoreItemsLabel]=\"'Load more asset properties' | translate\"\n  [loadingItemsLabel]=\"'Loading asset properties\u2026' | translate\"\n  [displayOptions]=\"displayOptions\"\n  [headerActionControls]=\"headerActionControls\"\n  [columns]=\"columns\"\n  [treeGrid]=\"true\"\n  [childNodePagination]=\"childNodePagination\"\n  parentNodeLabelProperty=\"title\"\n  [pagination]=\"pagination\"\n  [serverSideDataCallback]=\"serverSideDataCallback\"\n  [selectable]=\"true\"\n  [singleSelection]=\"true\"\n  (itemsSelect)=\"selectItem($event)\"\n></c8y-data-grid>\n<div class=\"card-footer p-24 separator text-center\">\n  <button\n    class=\"btn btn-default\"\n    type=\"button\"\n    (click)=\"close()\"\n  >\n    {{ ' Cancel' | translate }}\n  </button>\n</div>\n" }]
        }], ctorParameters: () => [{ type: AssetPropertyService }, { type: BottomDrawerRef }, { type: AlertService }], propDecorators: { onAddCustomColumn: [{
                type: Output
            }] } });

export { AssetPropertyGridComponent };
//# sourceMappingURL=c8y-ngx-components-asset-property-grid.component-BJOPTjF1.mjs.map
