import pugPlugin from '@11ty/eleventy-plugin-pug'
import rssPlugin from '@11ty/eleventy-plugin-rss'
import brokenLinksPlugin from 'eleventy-plugin-broken-links'
import { eleventyImageTransformPlugin } from '@11ty/eleventy-img'
import syntaxHighlight from '@11ty/eleventy-plugin-syntaxhighlight'
import footnote from 'markdown-it-footnote'
import fetch from 'node-fetch'
import fs from 'node:fs'
import exifParser from 'exif-parser'
import { EleventyRenderPlugin, IdAttributePlugin } from '@11ty/eleventy'
import { setupBlogCollections } from './scripts/eleventy/blog.js'
import { setupFeedCollections } from './scripts/eleventy/feed.js'

const setupDirectories = eleventyConfig => {
    eleventyConfig.setInputDirectory('src')
    eleventyConfig.addPassthroughCopy('src/assets/**')
    eleventyConfig.addPassthroughCopy('src/favicon.ico')
}

const setupPlugins = eleventyConfig => {
    eleventyConfig.addPlugin(brokenLinksPlugin)
    eleventyConfig.addPlugin(pugPlugin)
    eleventyConfig.addPlugin(rssPlugin)
    eleventyConfig.addPlugin(syntaxHighlight)
    eleventyConfig.addPlugin(IdAttributePlugin)
    eleventyConfig.addPlugin(EleventyRenderPlugin)
    eleventyConfig.amendLibrary('md', md => md.use(footnote))
    /*eleventyConfig.addPlugin(eleventyImageTransformPlugin, {
        htmlOptions: {
            imgAttributes: {
                alt: '',
            },
        },
    })*/

    eleventyConfig.addLiquidFilter('dateToRfc822', rssPlugin.dateToRfc822)
    eleventyConfig.addLiquidFilter('dateToRfc3339', rssPlugin.dateToRfc3339)
    eleventyConfig.addLiquidFilter('getNewestCollectionItemDate', rssPlugin.getNewestCollectionItemDate)

    eleventyConfig.addLiquidFilter('parseExif', async (src) => {
        const content = src.startsWith('https://')
            ? await fetch(src).then(r => r.arrayBuffer())
            : fs.readFileSync(src)

        const result = exifParser.create(content).parse()
        console.log({ result })
        return result
    })
}

export default function (eleventyConfig) {
    setupPlugins(eleventyConfig)
    setupDirectories(eleventyConfig)
    setupBlogCollections(eleventyConfig)
    setupFeedCollections(eleventyConfig)
}
