// @ts-check

/**
 * Generate component/route src folder and files from template/s
 *
 * @param {Object} options
 * @param {string} options.name
 * @param {Object} options.data
 * @param {string} [options.srcFolder]
 * @param {string} [options.srcFilename]
 * @param {string} options.destFolder
 * @param {string} [options.destFilename]
 */
function generate({
  name,
  data,
  srcFolder,
  srcFilename,
  destFolder,
  destFilename,
}) {
  const fs = require("fs");
  const path = require("path");
  const paths = require("../paths");

  if (!fs.existsSync(destFolder)) {
    fs.mkdirSync(destFolder);
  }

  const generatedFolder = path.join(destFolder, name);

  if (!fs.existsSync(generatedFolder)) {
    fs.mkdirSync(generatedFolder);
  }
  /// start from a single template file
  if (srcFilename) {
    generateFromTpl(path.join(paths.self.templates, srcFilename), {
      data,
      srcFolder: paths.self.templates,
      generatedFolder,
      destFilename,
    });
    // or use all template files in the given folder
  } else if (srcFolder) {
    fs.readdirSync(path.join(paths.self.templates, srcFolder)).forEach(
      (tplPath) => {
        generateFromTpl(tplPath, {
          data,
          srcFolder: path.join(paths.self.templates, srcFolder),
          generatedFolder,
          destFilename,
        });
      }
    );
  }
}

/**
 * Generate from single template file
 *
 * @param {string} tplPath
 * @param {Object} options
 * @param {Object} options.data
 * @param {string} options.srcFolder
 * @param {string} options.generatedFolder
 * @param {string} [options.destFilename]
 */
function generateFromTpl(
  tplPath,
  { data, srcFolder, generatedFolder, destFilename }
) {
  const fs = require("fs");
  const path = require("path");
  const _template = require("lodash.template");
  const tplFullpath = path.join(srcFolder, tplPath);
  const tplFilename = path.basename(tplFullpath);
  const tplContent = fs.readFileSync(tplFullpath, "utf-8");
  const tplCompiled = _template(tplContent);
  const generatedContent = tplCompiled(data);
  const generatedPath = path.join(generatedFolder, destFilename || tplFilename);

  fs.writeFileSync(generatedPath, generatedContent);
}

module.exports = {
  generate,
};
