import path from 'path';
import prettier from 'prettier';
import pugPlugin from "@11ty/eleventy-plugin-pug";
import sass from 'sass';
import {deleteSync} from 'del';

export default function(eleventyConfig) {
  deleteSync('_site/*');
  eleventyConfig.setInputDirectory('src');
  eleventyConfig.addPlugin(pugPlugin);
  eleventyConfig.addPassthroughCopy('src/styles/bulma.min.css', {debug: true});
  eleventyConfig.addPassthroughCopy('src/images/*', {debug: true});
  eleventyConfig.addPassthroughCopy('src/fonts/*', {debug: true});
  eleventyConfig.addTemplateFormats("sass");
  eleventyConfig.addExtension("sass", {
    outputFileExtension: "css",
    useLayouts: false,
    compile: async function (inputContent, inputPath) {
      let parsed = path.parse(inputPath);
      if(parsed.name.startsWith("_")) {
        return;
      }
      let result = sass.compileString(inputContent, {
        loadPaths: [
          parsed.dir || ".",
          this.config.dir.includes,
        ],
        syntax: 'indented',
      });
      this.addDependencies(inputPath, result.loadedUrls);
      return async (data) => {
        return result.css;
      };
    },
  });
  eleventyConfig.addNunjucksAsyncShortcode('svgIcon', async (src, alt, sizes) => {
    let metadata = await Image(src, {
      formats: ['svg'],
      dryRun: true,
    });
    return metadata.svg[0].buffer.toString();
  });
  eleventyConfig.addTransform("prettier", function (content) {
    if ((this.page.outputPath || "").endsWith(".html")) {
      let prettified = prettier.format(content, {
        bracketSameLine: true,
        printWidth: 512,
        parser: "html",
        tabWidth: 2
      });
      return prettified;
    }

    // If not an HTML output, return content as-is
    return content;
  });
};
