const fs = require('fs');
const pages = require('./pages');

// Index
const srcIndex = 'src/index.html';
const srcIndexConfig = 'src/index.json';
// Where to put it
const distIndex = 'dist/index.html'

// Actual processing
function run() {
    const config = indexConfig();

    // Community
    const community = [];
    const configCommunity = config['community'];
    Object.keys(configCommunity).forEach((c) => {
        community.push(`<li><p class="content"><a href="${configCommunity[c]}">${c}</a></p></li>`);
    });

    // Pages
    const other = [];
    pages.getPages().forEach((page) => {
        other.push(`<li><p class="content"><a href="${page.path}">${page.title}</a></p></li>`);
    });

    fs.writeFileSync(distIndex, buildIndex(community, other))
}

const indexTemplate = fs.readFileSync(srcIndex).toString();

// Inject the config
function buildIndex(community, pages) {
    return indexTemplate
        .replace('{{community}}', community)
        .replace('{{pages}}', pages)
}

// Module stuff
function indexConfig() {
    const contents = fs.readFileSync(srcIndexConfig);
    return JSON.parse(contents.toString());
}

module.exports = { indexConfig };

// Run the h*ckin' thing
if (require.main === module) {
    run();
}
