#!/usr/bin/env node

/**
 * This example script expects a JSON blob generated by react-docgen as input, 
 * e.g. react-docgen components/* | buildDocs.sh
 */

var fs = require('fs');
var generateMarkdown = require('./generateMarkdown');
var path = require('path');

var json = '';
process.stdin.setEncoding('utf8');
process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
  if (chunk !== null) {
    json += chunk;
  }
});

process.stdin.on('end', function() {
  buildDocs(JSON.parse(json));
});

function buildDocs(api) {
  // api is an object keyed by filepath. We use the file name as component name.
  var i = 0;
  for (var filepath in api) {
    console.log(filepath)
    var targetDir = 'docs/components/';
    var name = getComponentName(filepath);
    var markdown = generateMarkdown(name, api[filepath]);
    fs.writeFileSync(targetDir + name + '.md', markdown);
    process.stdout.write(filepath + ' -> ' + targetDir + name + '.md\n');
    i++;
  }
}

function getComponentName(filepath) {
  var name = path.dirname(filepath).split(path.sep).pop();
  return name;
}