import fs from "fs";
import * as opml from "opml";

const sortArrayOfObjectsByProperty = (arr, prop, desc=false) => {
    const direction = desc ? -1 : 1
    return arr.sort((a, b) => {
        if ( a[prop] < b[prop] ) return -1 * direction
        if ( a[prop] > b[prop] ) return 1 * direction
        return 0
    })
}

export const setupBlogCollections = eleventyConfig => {
    eleventyConfig.addCollection("blogByYear", api => {
        const postsByYear = {}
        const posts = api.getFilteredByTag('blog')
        const years = []
        for ( const post of posts ) {
            const year = post.date.getFullYear()
            if ( !postsByYear[year] ) postsByYear[year] = []
            postsByYear[year] = [post, ...postsByYear[year]]
            if ( !years.includes(year) ) years.push(year)
        }

        return years.sort().reverse().map(year => ({
            year,
            posts: postsByYear[year],
        }))
    })

    eleventyConfig.addCollection("blogByTag", api => {
        const postsByTag = {}
        const posts = api.getFilteredByTag('blog')
        const tags = []
        for ( const post of posts ) {
            for ( const tag of post.data.blogtags || [] ) {
                if ( !postsByTag[tag] ) postsByTag[tag] = []
                postsByTag[tag].push(post)
                if ( !tags.includes(tag) ) tags.push(tag)
            }
        }

        return tags
            .sort()
            .map(tag => ({
                tag,
                posts: postsByTag[tag].reverse(),
            }))
    })

    eleventyConfig.addCollection("opmlByCategory", async api => {
        const xml = fs.readFileSync("./src/assets/rss_opml.xml")
        const parsed = await new Promise((res, rej) => {
            opml.parse(xml, (err, doc) => err ? rej(err) : res(doc))
        })

        let subs = parsed.opml.body.subs
        subs = sortArrayOfObjectsByProperty(subs, 'title')
        subs.forEach(cat => cat.subs = sortArrayOfObjectsByProperty(cat.subs, 'title'))
        return subs
    })
}
