import API from "../../Utils/API/API";
import ModelAPI from "../../Utils/ModelAPI/ModelAPI";
import Page from "./Page";
import React, { useState } from "react";
import useAsyncEffect from "use-async-effect";
const ModelPage = (props) => {
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState("");
    const [labels, setLabels] = useState([]);
    const fetchItem = async () => {
        var _a, _b;
        // get item.
        setIsLoading(true);
        setError("");
        try {
            const modelInstance = new props.modelType();
            const labelsColumn = modelInstance.getAccessControlColumn();
            const select = {
                [props.modelNameField]: true,
            };
            if (labelsColumn) {
                select[labelsColumn] = {
                    _id: true,
                    name: true,
                    color: true,
                };
            }
            const modelAPI = props.modelAPI || ModelAPI;
            const item = await modelAPI.getItem({
                modelType: props.modelType,
                id: props.modelId,
                select: select,
                requestOptions: {},
            });
            if (!item) {
                setError(`Cannot load ${(((_a = new props.modelType()) === null || _a === void 0 ? void 0 : _a.singularName) || "item").toLowerCase()}. It could be because you don't have enough permissions to read this ${(((_b = new props.modelType()) === null || _b === void 0 ? void 0 : _b.singularName) || "item").toLowerCase()}.`);
                return;
            }
            if (labelsColumn) {
                const columnValue = item.getColumnValue(labelsColumn);
                const loadedLabels = columnValue || item[labelsColumn] || [];
                setLabels(loadedLabels);
            }
            else {
                setLabels([]);
            }
            setTitle(`${props.title || ""} - ${item[props.modelNameField]}`);
        }
        catch (err) {
            setLabels([]);
            setError(API.getFriendlyMessage(err));
        }
        setIsLoading(false);
    };
    const [title, setTitle] = useState(props.title);
    useAsyncEffect(async () => {
        // fetch the model
        await fetchItem();
    }, []);
    return (React.createElement(Page, Object.assign({}, props, { labels: labels.length > 0 ? labels : undefined, isLoading: isLoading, error: error, title: title })));
};
export default ModelPage;
//# sourceMappingURL=ModelPage.js.map