const { DateTime } = require("luxon");
const markdownIt = require("markdown-it");
const markdownItFootnote = require("markdown-it-footnote");
const markdownItAnchor = require("markdown-it-anchor");
const mdfigcaption = require('markdown-it-image-figures');
const pluginRss = require("@11ty/eleventy-plugin-rss");
const pluginSyntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");
const pluginBundle = require("@11ty/eleventy-plugin-bundle");
const pluginNavigation = require("@11ty/eleventy-navigation");
const { EleventyHtmlBasePlugin } = require("@11ty/eleventy");

const figoptions = {
	figcaption: true
};

module.exports = function(eleventyConfig) {

	// Helper Functions
	const multiReplace = (text, replacementTable) => {
		let newText = text;
		replacementTable.forEach(x => { newText = newText.replace(x[0], x[1]) });
		return newText;
	};

	eleventyConfig.addWatchTarget("content/**/*.{svg,webp,png,jpeg}");

	// Official plugins
	eleventyConfig.addPlugin(pluginRss);
	eleventyConfig.addPlugin(pluginSyntaxHighlight, {
		preAttributes: { tabindex: 0 }
	});
	eleventyConfig.addPlugin(pluginNavigation);
	eleventyConfig.addPlugin(EleventyHtmlBasePlugin);
	eleventyConfig.addPlugin(pluginBundle);

	// Filters
	eleventyConfig.addFilter("readableDate", (dateObj, format, zone) => {
		// Formatting tokens for Luxon: https://moment.github.io/luxon/#/formatting?id=table-of-tokens
		return DateTime.fromJSDate(dateObj, { zone: zone || "utc" }).toFormat(format || "dd LLLL yyyy");
	});

	eleventyConfig.addFilter('htmlDateString', (dateObj) => {
		// dateObj input: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
		return DateTime.fromJSDate(dateObj, { zone: 'utc' }).toFormat('yyyy-LL-dd');
	});

	// Shortcodes
	eleventyConfig.addNunjucksFilter("cowsay", cowText => {
		const cowCaptionReplacementTable = [
			[`
					o   ^__^
					 o  (oo)\\_______
							(__)\\       )\\/\\
									||----w |
									||     ||`, ''],
			[/\(\s+/g, ''],
			[/\s+\(/g, ''],
			[/_{3,}/g, ''],
			[/-{3,}/g, ''],
			[/\s\)/g, ''],
			[/\n/g, ''],
			[/\s{2,}/g, ' '],
			[/^ /, '']
		];

		return `
<figure>
  <pre class="language-" role="img" aria-label="ASCII COW">${cowText}</pre>
  <figcaption id="cow-caption">
    A cow thinking: <em>${multiReplace(cowText, cowCaptionReplacementTable)}</em>. The cow is illustrated using
    preformatted text characters.
  </figcaption>
</figure>
			`;
	});

	// Passthrough
	eleventyConfig.addPassthroughCopy({ 'public/xsl/*': "/xsl/" });
	eleventyConfig.addPassthroughCopy({ 'public/img/*': "/img/" });
	eleventyConfig.addPassthroughCopy({ 'public/robots.txt': "/" });
	eleventyConfig.addPassthroughCopy({ 'public/js/*': "/js/" });
	eleventyConfig.addPassthroughCopy({ 'public/js/webComponents/*': "/js/webComponents" });
	// Copying so that basic.xsl can use it
	eleventyConfig.addPassthroughCopy({ 'public/css/index.css': "/css/index.css" });
	eleventyConfig.addPassthroughCopy({ 'public/css/webfonts/*': "/css/webfonts/" });

	// Get the first `n` elements of a collection.
	eleventyConfig.addFilter("head", (array, n) => {
		if (!Array.isArray(array) || array.length === 0) {
			return [];
		}
		if (n < 0) {
			return array.slice(n);
		}

		return array.slice(0, n);
	});

	// Return the smallest number argument
	eleventyConfig.addFilter("min", (...numbers) => {
		return Math.min.apply(null, numbers);
	});

	// Return all the tags used in a collection
	eleventyConfig.addFilter("getAllTags", collection => {
		let tagSet = new Set();
		for (let item of collection) {
			(item.data.tags || []).forEach(tag => tagSet.add(tag));
		}
		return Array.from(tagSet);
	});

	eleventyConfig.addFilter("filterTagList", function filterTagList(tags) {
		return (tags || []).filter(tag => ["all", "nav", "post", "posts"].indexOf(tag) === -1);
	});

	// Customize Markdown library settings:
	eleventyConfig.amendLibrary("md", mdLib => {
		mdLib.use(markdownItAnchor, {
			permalink: markdownItAnchor.permalink.ariaHidden({
				placement: "after",
				class: "header-anchor",
				symbol: "#",
				ariaHidden: false,	// Features to make your build faster (when you need them)

				// If your passthrough copy gets heavy and cumbersome, add this line
				// to emulate the file copy on the dev server. Learn more:
				// https://www.11ty.dev/docs/copy/#emulate-passthrough-copy-during-serve

				// eleventyConfig.setServerPassthroughCopyBehavior("passthrough");
			}),
			level: [1, 2, 3, 4],
			slugify: eleventyConfig.getFilter("slugify")
		}).use(markdownItFootnote).use(mdfigcaption, figoptions);
	});

	return {
		templateFormats: [
			"md",
			"njk",
			"html",
			"liquid",
		],

		markdownTemplateEngine: "njk",

		htmlTemplateEngine: "njk",

		dir: {
			input: "content",          // default: "."
			includes: "../_includes",  // default: "_includes"
			data: "../_data",          // default: "_data"
			output: "_site"
		},
		pathPrefix: "/",
	};
};
