import { DateTime } from "luxon";
import emojiReadTime from "@11tyrocks/eleventy-plugin-emoji-readtime";
import markdownIt from "markdown-it";
import markdownItFootnote from "markdown-it-footnote";
import markdownItContainer from "markdown-it-container";
import markdownItAnchor from "markdown-it-anchor";
import mdfigcaption from "markdown-it-image-figures";
import pluginRss from "@11ty/eleventy-plugin-rss";
import pluginSyntaxHighlight from "@11ty/eleventy-plugin-syntaxhighlight";
import pluginBundle from "@11ty/eleventy-plugin-bundle";
import pluginNavigation from "@11ty/eleventy-navigation";
import prettier from "prettier";
import { EleventyHtmlBasePlugin } from "@11ty/eleventy";
import { dateSuffixAdder, monthMap } from "./public/js/modules/dateTools.js";

const figoptions = {
	figcaption: true,
};

export default async function (eleventyConfig) {
	// Customize Markdown library settings:
	let markdownItOptions = {
		html: true,
		typographer: true,
	};

	let mdLib = markdownIt(markdownItOptions);

	eleventyConfig.amendLibrary("md", (mdLib) => {
		mdLib
			.use(markdownItAnchor, {
				permalink: markdownItAnchor.permalink.ariaHidden({
					placement: "after",
					class: "header-anchor",
					symbol: "#",
					ariaHidden: false,
				}),
				level: [1, 2, 3, 4],
				slugify: eleventyConfig.getFilter("slugify"),
			})
			.use(markdownItFootnote)
			.use(mdfigcaption, figoptions)
			.use(markdownItContainer, "info");
	});

	eleventyConfig.setLibrary("md", mdLib);

	// Collections
	eleventyConfig.addCollection("galleryImages", (collection) => {
		const galleries = collection.getAll()[0].data.galleries;
		let galleryImages = [];

		galleries.forEach((gallery) => {
			gallery.pictures.forEach((picture, i, arr) => {
				picture.containingGallery = `${gallery.title}`;
				picture.baseUrl = `${gallery.url}`;
				i ? (picture.previousImage = arr[i - 1].filename) : null;
				i + 1 != arr.length ? (picture.nextImage = arr[i + 1].filename) : null;
				galleryImages.push(picture);
			});
		});

		return galleryImages;
	});

	eleventyConfig.addCollection("feed", async (collectionApi) => {
		return [
			...collectionApi.getFilteredByTag("posts"),
			...collectionApi.getFilteredByTag("now"),
		].sort(function (a, b) {
			return b.date - a.date;
		});
	});

	eleventyConfig.addCollection("onceBurned", async (collectionApi) => {
		const arr = [...collectionApi.getFilteredByTag("nowBurning")].sort(
			function (a, b) {
				return b.date - a.date;
			},
		);
		return arr.slice(1, arr.length);
	});

	eleventyConfig.addCollection("priorThoughts", async (collectionApi) => {
		const arr = [...collectionApi.getFilteredByTag("status")].sort(
			function (a, b) {
				return b.date - a.date;
			},
		);
		return arr.slice(1, arr.length);
	});

	// Transforms
	eleventyConfig.addTransform("prettier", function (content, outputPath) {
		if (outputPath && outputPath.endsWith(".html")) {
			return prettier.format(content, {
				parser: "html",
				bracketSameLine: true,
				vueIndentScriptAndStyle: true,
				singleAttributePerLine: true,
				htmlWhitespaceSensitivity: "css",
			});
		} else {
			return content;
		}
	});

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

	// Plugins
	eleventyConfig.addPlugin(pluginRss);
	eleventyConfig.addPlugin(pluginSyntaxHighlight, {
		preAttributes: { tabindex: 0 },
	});
	eleventyConfig.addPlugin(pluginNavigation);
	eleventyConfig.addPlugin(EleventyHtmlBasePlugin);
	eleventyConfig.addPlugin(pluginBundle);
	eleventyConfig.addPlugin(emojiReadTime, {
		label: "minute read time",
	});

	// Filters
	eleventyConfig.addFilter("niceDate", (date) => {
		var day = new Date(date).getUTCDate();
		var monthIndex = new Date(date).getUTCMonth();
		var year = new Date(date).getUTCFullYear();

		return `${day}${dateSuffixAdder(day)} of ${monthMap[monthIndex]}, ${year}`;
	});

	eleventyConfig.addFilter("htmlDateString", (dateObj) => {
		return DateTime.fromJSDate(dateObj, { zone: "utc" }).toFormat("yyyy-LL-dd");
	});

	// Remove most recent item added to array
	eleventyConfig.addFilter("removeMostRecent", (arr) => {
		return arr.slice(0, arr.length - 1);
	});

	eleventyConfig.addFilter("abbr", (abbr, def) => {
		return `<abbr title="${def}">${abbr}</abbr>`;
	});

	eleventyConfig.addFilter("markdownify", (markdownString) => {
		return mdLib.renderInline(markdownString);
	});

	// Shortcodes
	// Audio player
	eleventyConfig.addShortcode(
		"audio",
		function (title, artist, media_url, cover_url) {
			return `
				<figure class="mplayer">
					<div class="coverContainer">
						<img src="${cover_url}" class="albumCover">
					</div>
					<div class="captionAndPlayer">
						<figcaption class="mplayerInfo">
							<span class="songTitle">${title}</span><br /><span class="artist">${artist}</span>
						</figcaption>
						<audio controls src="${media_url}" class="player"></audio>
					</div>
				</figure>
		`;
		},
	);

	// Passthrough
	eleventyConfig
		.addPassthroughCopy({ "./public/": "/" })
		.addPassthroughCopy("./content/special/");

	// 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",
					"gallery",
					"quiz",
					"nowBurning",
				].indexOf(tag) === -1,
		);
	});

	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: "/",
	};
}
