const reactDocs = require("react-docgen");
const fs = require("fs");

const propDocs = {}

const generateProps = (baseURL, propDocs, componentName = "AxiomComponent") => {

    const excludedFolders = [
        "tests",
        "examples",
        "example",
        "mock_api",
        "__snapshots__",
        "Deprecated",
        "ExampleComponent",
        "Icon", // Icons are not exported from Axiom so we can ignore it.
        "Array" // Contains no js code.
    ];
    const includedFiles = [".js", ".tsx"];
    // There is some inconsistent usage of files in each component, so we have to ignore some edge cases. Ideally these files should be in folders that we can ignore.
    const excludedFiles = [".story.js", ".story.tsx", ".story.jsx", ".test.tsx", ".json", "draggableTypes.js", "constants.js"];

    // Some index.js files can't be parsed since they are not following the convention, these are:
    // CodeDiff index.js
    // FilterPicker index.js
    // AccountSwitcher index.js
    // Pagination index.js
    // Sidebar index.js

    fs.readdirSync(baseURL)
        .forEach(filename => {

            const _url = `${baseURL}/${filename}`;

            const _stat = fs.statSync(_url);

            const exists = file => filename.includes(file);

            if (_stat && _stat.isDirectory() && !excludedFolders.includes(filename)) {
                generateProps(_url, propDocs, filename);
            } else if (
                includedFiles.some(exists) &&
                !excludedFiles.some(exists)
            ) {
                try {
                    propDocs[componentName] = reactDocs.parse(fs.readFileSync(_url, "utf-8"), reactDocs.resolver.findAllComponentDefinitions, undefined, { filename });
                } catch (e) {
                    console.log("couldn't parse:", componentName, filename);
                }

            }
        });
};

generateProps("src/components", propDocs);

fs.writeFileSync(`data/components.json`, JSON.stringify(propDocs, null, 4));
