import Mustache from "mustache";
import {stripHtml} from "../../helpers";

export function previewTitle(schemas, record, graph) {
    let schema = schemas.find((aSchema) => aSchema.name === record?.schema);
    if (!schema?.cardTitle) {
        return noTemplate(schema, record);
    }

    let recordData = record.data;
    let render = Mustache.render(schema.cardTitle, recordData);
    if (!render || render === "") {
        return noTemplate(schema, record);
    }

    return stripHtml(render.slice(0, 300));
}

function noTemplate(schema, record) {
    if (schema?.type === "files") {
        return record._file.path;
    }

    let title =  stripHtml(
        record?.data[schema.fields.filter((f) => f.info.name === "text")[0]?.name]
    ).slice(0, 300);

    if(title.trim() === ""){
        return "~Untitled~";
    }

    return title;
}
