const { I18nPlugin } = require("@11ty/eleventy");
const i18n = require("eleventy-plugin-i18n");
const eleventySass = require("eleventy-sass");
const toml = require("@iarna/toml");

const fs = require("fs");
const path = require("path");

module.exports = function(eleventyConfig) {
    eleventyConfig.setLayoutsDirectory("_layouts");
    eleventyConfig.addPassthroughCopy("img");
    eleventyConfig.addPassthroughCopy("css/fonts");
    eleventyConfig.addPassthroughCopy("js");
    eleventyConfig.addPassthroughCopy("LICENSE.txt");
    eleventyConfig.addPassthroughCopy("robots.txt");

    eleventyConfig.addNunjucksFilter("values", obj => Object.values(obj));

    eleventyConfig.addFilter("i18n_filter", function(collection, limit = null) {
        const lang = this.page.lang; // access page.lang from context
        let filtered = collection.filter(item => item.data.lang === lang);
        if (limit !== null) {
            filtered = filtered.slice(0, limit);
        }
        return filtered;
    });

    eleventyConfig.addPlugin(eleventySass);
    eleventyConfig.addPlugin(I18nPlugin, {
        defaultLanguage: "en",
        errorMode: "allow-fallback" // /en/ -> /
    });
    eleventyConfig.addDataExtension("toml", (contents) => toml.parse(contents));

    const translationsToml = fs.readFileSync(
        path.join(__dirname, "_data", "locale.toml"),
        "utf-8"
    );
    const translations = toml.parse(translationsToml);

    eleventyConfig.addPlugin(i18n, {
        translations,
        fallbackLocales: {
            "*": "en",
        }
    });

    return {
        markdownTemplateEngine: "njk",
        htmlTemplateEngine: "njk"
    }
};