dare to have fun

const path = require("path");

function fileLink(file, name = undefined) {
    /* returns string of relative wikilink */
    const fromHere = dv.current().file.path;
    const toThere = file?.file?.path ?? file;
    const relativePath = path.relative(path.dirname(fromHere), toThere);
    const toThereBasename = path.parse(toThere).name;
    return `[[${relativePath}|${name ?? toThereBasename}]]`;
}

function recipeType(recipe) {
    /* returns list of recipe's [supertype, type] */
    return path.parse(recipe.file.path).dir.split("/").slice(-2);
}

function recipeTypeLink(recipe) {
    const indexFile = "/index";
    const supertypeIndexPath =
        path.parse(recipe.file.path).dir.split("/").slice(0, -1).join("/") +
        indexFile;
    const typeIndexPath = path.parse(recipe.file.path).dir + indexFile;

    const supertypeIndexLink = fileLink(
        supertypeIndexPath,
        recipeType(recipe)[0],
    );
    const typeIndexLink = fileLink(typeIndexPath, recipeType(recipe)[1]);

	return `${supertypeIndexLink}/${typeIndexLink}`;
}

function recipeExperience(recipeTags) {
    /* list of recipe tags transform into string */
    if (recipeTags.length > 1) {
        return recipeTags.map((tag) => "#" + tag).join(" ");
    }
}

const headers = [
    path.parse(dv.current().file.path).dir.split("/").slice(-1).join(),
    "type",
    "experience",
];

const values = dv
    .pages()
    .where((page) => page.file.path.includes(dv.current().file.folder))
    .where((page) => page["item-type"] === "recipe")
    .where((page) => page["publish"] === true)
    .sort((recipe) => recipe.name ?? recipe.file.name, "asc")
    .sort((recipe) => recipeType(recipe)[1], "asc")
    .sort((recipe) => recipeType(recipe)[0], "asc")
    .map((recipe) => [
        fileLink(recipe),
        recipeTypeLink(recipe),
        recipeExperience(recipe.tags),
    ]);

const table = dv.markdownTable(headers, values);

dv.paragraph(table);

table