import pluginWebc from '@11ty/eleventy-plugin-webc'
import mdit from 'markdown-it'
import i18n from 'eleventy-plugin-i18n'
import fs from 'fs/promises'

const MD_REGEX = /\.[^/.]{1,4}$/i

export default function (config) {
  // markdown parser
  const markdownLib = mdit({
    html: true,
    breaks: false,
    linkify: true,
  }).disable('code')

  config.setLibrary('md', markdownLib)

  // i18n
  config.addPlugin(i18n, {
    fallbackLocales: {
      '*': 'en'
    }
  })

  // webc templates
  config.addPlugin(pluginWebc, {
    components: 'src/layouts/components/*.webc',
  })

  config.addPassthroughCopy({
    'src/assets': '/',
    'src/admin': '/admin',
  })

  // add collection for pages
  config.addCollection('categories', async (collection) => {
    const languages = (await fs.readdir('src/content/'))
    const categories = new Map()

    for (const lang of languages) {
      const categoryNames = (await fs.readdir(`src/content/${lang}`, { withFileTypes: true })).filter((dirent) => !dirent.isFile()).map(v => v.name)

      categories.set(lang, new Map())

      for (const catName of categoryNames) {
        const langCategory = categories.get(lang)
        categories.set(lang, collection.getFilteredByGlob(`src/content/${lang}/${catName}/index.md`).reduce((accumulator, category) => {
          accumulator.set(category, [])

          return accumulator
        }, langCategory))


        categories.set(lang, collection.getFilteredByGlob(`src/content/${lang}/${catName}/*.md`).reduce((accumulator, category) => {
          const categoryIsKey = accumulator.keys().find(key => category === key)
          if (!categoryIsKey) {
            const categoryKey = accumulator.keys().find(key => category.data.tags.includes(key.data.tags[0]))
            const catAccum = accumulator.get(categoryKey)
            catAccum.push(category)
          }

          return accumulator
        }, langCategory))
      }
    }

    const cols = { en: map2arr(categories.get('en')), fr: map2arr(categories.get('fr')) }
    return cols
  })

  config.addCollection('pages', async (collection) => {
    const languages = (await fs.readdir('src/content/')).filter((c) => !c.match(MD_REGEX))
    const pages = {}

    for (const lang of languages) {
      pages[lang] = collection.getFilteredByGlob(`src/content/${lang}/*.md`).filter(p => !p.page.fileSlug.match(lang))
    }

    return pages
  })

  // added passthrough for images in their respective folders
  config.addPassthroughCopy('src/content/**/*.jpg')
  config.addPassthroughCopy('src/content/**/*.png')
  config.addPassthroughCopy('src/content/**/*.gif')
  config.addPassthroughCopy('src/content/**/*.webp')

  return {
    markdownTemplateEngine: 'md',
    dir: {
      input: 'src/content',
      includes: '../layouts',
      data: '../data',
      output: 'dist',
    },
  }
}

const map2arr = (myMap) => {
  const arr = []
  myMap.forEach((value, key) => {
    arr.push([key, value])
  })
  return arr
}