import fs from 'fs'
import fm from 'front-matter'
import showdown from 'showdown'
import { toSlug } from './helpers'

export function getMarkdownEntry (path) {
  const fileContents = fs.readFileSync(path, {
    encoding: 'utf-8'
  })

  const { attributes, body } = fm(fileContents)

  const converter = new showdown.Converter({
    tables: true,
    tablesHeaderId: true
  })
  const html = converter.makeHtml(body)

  const slug = toSlug(path.substring(path.lastIndexOf('/') + 1))

  return {
    attributes: {
      ...attributes,
      pubdate: attributes.pubdate?.toUTCString() ?? null,
      moddate: attributes.moddate?.toUTCString() ?? null
    },
    html,
    slug
  }
}

export function getStaticEntryPaths (contentPath) {
  const entries = fs.readdirSync(contentPath, { withFileTypes: true })

  const paths = entries.map((dirent) => ({
    params: {
      slug: toSlug(dirent.name)
    }
  }))

  return {
    fallback: false,
    paths
  }
}

export function getStaticEntryProps (contentPath, { params }) {
  const path = `${contentPath}/${params.slug}.md`
  const entry = getMarkdownEntry(path)
  const { attributes } = entry

  return { props: { ...entry, attributes } }
}

export function getStaticEntries (contentPath) {
  const directoryItems = fs.readdirSync(contentPath, { withFileTypes: true })
  return directoryItems.map((dirent) =>
    getMarkdownEntry(`${dirent.path}/${dirent.name}`)
  );
}

export function getContentTags (contentPath) {
  const allTags = {}

  const entries = getStaticEntries(contentPath)
  for (const entry of entries) {
    if (!entry.attributes.tags) { continue }

    const tags = entry.attributes.tags.split(', ')

    for (const tag of tags) {
      allTags[tag] = !allTags[tag] ? 1 : allTags[tag] + 1
    }
  }

  return allTags
}
