import { jsx as _jsx } from "react/jsx-runtime";
import renderers from './renderers';
const defaultRenderer = renderers.string();
function resolveField(object, path) {
    let p = object;
    if (!p)
        return undefined;
    if (!path.length)
        return p;
    const last = path.length - 1;
    for (let i = 0; i < last; i++) {
        p = p[path[i]];
        if (!p) {
            return undefined;
        }
    }
    return p[path[last]];
}
function splitPath(path) {
    if (!path || path === '.') {
        return [];
    }
    return path.split('.');
}
export class DocumentTableColumn {
    layout;
    renderer = defaultRenderer;
    path;
    fallbackPath;
    previewObject;
    constructor(layout, previewObject) {
        this.layout = layout;
        this.path = splitPath(layout.field || '');
        this.fallbackPath = layout.fallback ? splitPath(layout.fallback) : undefined;
        this.previewObject = previewObject;
        // If there's a custom render function, use it
        if (layout.render) {
            this.renderer = (_value, _index) => null; // Placeholder, we'll use render directly
        }
        else {
            // Otherwise use the type-based renderer
            const type = layout.type || 'string';
            const i = type.indexOf('?');
            if (i > 0) {
                const name = type.substring(0, i);
                const params = new URLSearchParams(type.substring(i + 1));
                this.renderer = renderers[name](params);
            }
            else {
                this.renderer = renderers[type]();
            }
        }
    }
    get name() {
        return this.layout.name;
    }
    resolveValue(object) {
        let value = resolveField(object, this.path);
        if (value === undefined && this.fallbackPath) {
            value = resolveField(object, this.fallbackPath);
        }
        if (value === undefined) {
            value = this.layout.default;
        }
        return value;
    }
    render(object, index) {
        // If there's a custom render function, wrap its result in a td
        if (this.layout.render) {
            return _jsx("td", { className: "whitespace-nowrap px-3 py-4 text-sm", children: this.layout.render(object) }, index);
        }
        const type = this.layout.type || 'string';
        const baseType = type.indexOf('?') > 0 ? type.substring(0, type.indexOf('?')) : type;
        if (baseType === 'objectId' && this.previewObject) {
            const i = type.indexOf('?');
            const params = i > 0 ? new URLSearchParams(type.substring(i + 1)) : undefined;
            const objectIdRenderer = renderers.objectId(params, (_id) => {
                this.previewObject(object.id);
            });
            return objectIdRenderer(object, index);
        }
        // Otherwise use the type-based renderer with the resolved value
        return this.renderer(this.resolveValue(object), index);
    }
}
//# sourceMappingURL=DocumentTableColumn.js.map