const handlebarsPlugin = require("@11ty/eleventy-plugin-handlebars");
const handlebars = require('handlebars');
const sass = require("sass");
const pluginRss = require("@11ty/eleventy-plugin-rss");
const handlebarsHelpers = require('handlebars-helpers')
const { parseSync } = require('subtitle')
const path = require('path')


const htmlmin = require("html-minifier");

const utilsPlugin = require("./utils/plugin");
require('dotenv').config();

module.exports = function(eleventyConfig) {
  // Passthrough episodes directory to include both markdown and audio files
  eleventyConfig.addPassthroughCopy("content/episodes/*/*.mp3");
  eleventyConfig.addPassthroughCopy("content/episodes/**/*.jpg");
  eleventyConfig.addPassthroughCopy("content/episodes/**/*.webp");
  eleventyConfig.addPassthroughCopy("content/episodes/**/*.png");
  eleventyConfig.addPassthroughCopy("content/images");
  eleventyConfig.addPassthroughCopy("content/feeds/*.jpg");
  eleventyConfig.addPlugin(utilsPlugin, {immediate: true});
  eleventyConfig.addPlugin(handlebarsPlugin);
  eleventyConfig.addPlugin(pluginRss);

  eleventyConfig.addTemplateFormats("srt");
  eleventyConfig.addExtension(
    "srt",
    {compile: (inputContent, inputPath)=>{
    const parsed = parseSync(inputContent.toString(), {type:'srt'})
    return async (data) => {
      data.segments = parsed.map((i,idx)=>({id:idx, ...i.data}))
      data.layout = "transcript"
      // data.tags = ['transcript']
      return JSON.stringify(parsed.map((i,idx)=>({id:idx, ...i.data})))
    }
  }})
  
  
  handlebarsHelpers({
    handlebars
  })

  // eleventyConfig.addTransform("htmlmin", (content, outputPath) => {
  //   if (outputPath.endsWith(".html")) {
  //     return htmlmin.minify(content, {
  //       collapseWhitespace: true,
  //       removeComments: true,  
  //       useShortDoctype: true,
  //     });
  //   }

  //   return content;
  // });

  // Creates the extension for use
  eleventyConfig.addTemplateFormats("scss");
	eleventyConfig.addExtension("scss", {
		outputFileExtension: "css", // optional, default: "html"
		// `compile` is called once per .scss file in the input directory
		compile: async function (inputContent) {
			let result = sass.compileString(inputContent, {
				loadPaths: ["node_modules/bootstrap/scss", ] 
			});

			// This is the render function, `data` is the full data cascade
			return async (data) => result.css;
		},
	});

  return {
    pathPrefix: process.env.PATH_PREFIX || '/',
    dir: {
      data: "data",
      input: "content",
      includes: "../layouts"
    }
  };
};