const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const extract = require('./extract');

const readdirAsync = promisify(fs.readdir);
const readFileAsync = promisify(fs.readFile);
const writeFileAsync = promisify(fs.writeFile);

if (!process.env.MD_PATH) {
  console.log('process.env.MD_PATH must be defined');
}
const markdownPath = path.join(process.cwd(), process.env.MD_PATH);

async function run(filterFunc) {
  const allFiles = await readdirAsync(markdownPath);
  const tutoFiles = allFiles.filter(filterFunc);
  const promises = tutoFiles.map(async tuto => {
    const tutoPath = path.join(markdownPath, tuto);
    const buf = await readFileAsync(tutoPath);
    const md = buf.toString();
    console.log(md.substr(0, 10));
    try {
      return extract(md);
    } catch (err) {
      console.log(err.message);
    }
  });
  const tutos = await Promise.all(promises);
  const json = JSON.stringify(tutos);
  await writeFileAsync('lbac.json', json);
  process.exit();
}

const filterFunc = f => f.startsWith('tutor');

run(filterFunc);