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?.titleTemplate) {
        return noTemplate(schema, record);
    }

    let recordData = record.data;
    let template = Mustache.parse(schema.titleTemplate);

    let referencePreviews = template
        .filter(segment => segment[0] === "name") // keep only template tags
        .map((segment) => segment[1]) // map to fieldNames
        .filter(fieldName => { // keep only references
            let schemaField = schema.fields.find(f => f.name === fieldName)
            return schemaField?.info.name === "reference";
        }).reduce((carry, field) => {  // map to records
            let edge = graph.edges.find(edge => edge.source === record.id && edge.field === field)
            let referenceRecord = graph.records.find(rec => rec.id === edge?.target)
            carry[field] = previewTitle(schemas, referenceRecord, graph);
            return carry;
        }, {});
    recordData = {...recordData, ...referencePreviews}

    let render = Mustache.render(schema.titleTemplate, 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 == ""){
        return "Untitled";
    }

    return title;
}
