import {promises as fsp} from 'fs';
import {join} from 'path';
import cheerio from 'cheerio';
import {Feed} from 'feed';
import {PostList, months} from './html';

export async function generateFeeds(allPosts: PostList[]): Promise<void> {
  const feed = new Feed({
    title: 'Tildes Issue Log',
    description:
      'The Tildes Issue Log is a monthly blog about the development of Tildes.',
    id: 'https://til.bauke.xyz',
    link: 'https://til.bauke.xyz',
    language: 'en',
    image: 'https://til.bauke.xyz/android-chrome-192x192.png',
    favicon: 'https://til.bauke.xyz/favicon.ico',
    copyright:
      'AGPL-3.0-or-later Tildes Issue Log Contributors https://gitlab.com/Bauke/tildes-issue-log',
    generator: 'https://github.com/jpmonette/feed',
    feedLinks: {
      atom: 'https://til.bauke.xyz/feed.atom',
      json: 'https://til.bauke.xyz/feed.json',
      rss: 'https://til.bauke.xyz/feed.rss'
    },
    author: {
      name: 'Bauke',
      email: 'me@bauke.xyz',
      link: 'https://bauke.xyz'
    }
  });

  // Sort posts by most recent first.
  allPosts.sort((a, b) => b.year - a.year);
  for (const post of allPosts) {
    post.posts.sort((a, b) => b.month - a.month);
  }

  const maxPosts = 5;
  let postsAdded = 0;
  for (const year of allPosts) {
    if (postsAdded >= maxPosts) {
      break;
    }

    for (const post of year.posts) {
      if (postsAdded >= maxPosts) {
        break;
      }

      const month = `${months[post.month][0].toUpperCase()}${months[
        post.month
      ].slice(1)}`;
      const title = `${month} ${year.year}`;

      const id = `https://til.bauke.xyz/${year.year}/${
        months[post.month]
      }.html`;

      const date = new Date(year.year, post.month, 0, 12, 0, 0);

      const html: string = await fsp.readFile(
        join(__dirname, `../../public/${year.year}/${months[post.month]}.html`),
        'utf8'
      );
      const $: CheerioStatic = cheerio.load(html);
      const content: string = $('#post').html()!;

      feed.addItem({
        title,
        id,
        link: id,
        date,
        published: date,
        description: `${title}'s Issue Log`,
        content,
        image: 'https://til.bauke.xyz/android-chrome-192x192.png'
      });

      postsAdded++;
    }
  }

  const feedPath: string = join(__dirname, '../../public/feed');
  await fsp.writeFile(`${feedPath}.atom`, feed.atom1());
  await fsp.writeFile(`${feedPath}.json`, feed.json1());
  await fsp.writeFile(`${feedPath}.rss`, feed.rss2());
}
