module.exports = async (config) => {
    let isReady = false;
    const
        http = require('http'),

        chokidar = require('chokidar'),
        address = require('network-address'),
        handler = require('serve-handler'),

        build = require('./build'),
        rebuild = (cfg) => {
            isReady = false;
            build({ ...cfg, isRebuild: true });
            isReady = true;
        },

        { build: buildOpts, logFunction: log = () => {}, serve: serveOpts } = config || {},
        { outputPath, srcPath } = buildOpts || {},
        { port = 5000 } = serveOpts || {},

        watcher = chokidar.watch([srcPath, '*.json'],  {
            ignored: /(^|[\/\\])\../, // ignore dotfiles
            persistent: true
        })
        .on('add', (path) => {
            if (isReady) {
                log(`File ${path} has been added`)
                rebuild(config);
            }
        })
        .on('change', (path) => {
            if (isReady) {
                log(`File ${path} has been changed`)
                rebuild(config);
            }
        })
        .on('ready', () => {
            isReady = true;
        })
        .on('unlink', (path) => {
            if (isReady) {
                log(`File ${path} has been removed`)
                rebuild(config);
            }
        }),

        server = http.createServer((request, response) => {
            // You pass two more arguments for config and middleware
            // More details here: https://github.com/vercel/serve-handler#options
            return handler(request, response, { public: outputPath });
        });

    await build(config);
    
    server.listen(port, () => {
        log(`Running at http://${address()}:${port} / http://localhost:${port}`);
    });
};