const fs = require('fs');

const startPath = 'src/Assets/Svgs';
const rootRoute = '~/Assets/Svgs';
const findSvg = (render = (route, name) => {}, importRender = (route, name) => {}, path = startPath, route = '') => {

    const currentRoute = (route ? route : '/');
    const names = fs.readdirSync(path, { withFileTypes: true })
        .filter(file => file.isFile() && file.name.endsWith('.svg'))
        .map(file => {
            let name = file.name.replace('.svg', '');
            return {
                name: name, 
                filename: file.name, 
                routePath: rootRoute + route + '/' + file.name,
                importName: ('svgs' + route + '/' + name).replace(/[\/\-]/g, '_')
            };
        });
    if(names.length > 0) {
        render(currentRoute, names);
        importRender(currentRoute, names);
    }


    let result = '';
    const list = fs.readdirSync(path, { withFileTypes: true })
        .filter(dir => dir.isDirectory())
        .map(dir => dir.name);
    for(let dir of list) {
        findSvg(render, importRender, path + '/' + dir, route + '/' + dir);
    }
}

/* Generate Svgs */
const generateSvgs = () => {
    let svgs = '';
    let importers = '';
    findSvg((route, names) => {
        let svg = '';

        svg += `\t\t'${route}': {\n`;
        for(name of names) {
            svg += `\t\t\t'${name.name}': ${name.importName},\n`;
        }
        svg += `\t\t},\n`;

        svgs += svg;
    }, (route, names) => {
        for(name of names) {
            importers += `import ${name.importName} from '${name.routePath}';\n`;
        }
    });

    const string = `
${importers}

export const Svgs = {
${svgs}
};
`;
    
    fs.writeFileSync('src/Generated/Svgs.js', string, 'utf8');
}
generateSvgs();
