const jsonfile = require('jsonfile');
const path = require('path');

/**
 *
 * @param categories
 * @param parentTree
 */
function extractLeafCategories(categories, parentTree = '') {
  let result = [];

  categories.forEach((category) => {
    const currentTree = parentTree ? `${parentTree} > ${category.display_name}` : category.display_name;

    if (category.children && category.children.length > 0) {
      result = result.concat(extractLeafCategories(category.children, currentTree));
    } else {
      result.push({
        tree: currentTree,
        name: category.display_name,
        id: category.id,
        image: '',
      });
    }
  });

  return result;
}

const data = jsonfile.readFileSync(path.join(__dirname, './input.json'));
const categoryList = extractLeafCategories(data);
jsonfile.writeFileSync(path.join(__dirname, './output.json'), categoryList);
