"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const CompactdApplication_1 = require("./CompactdApplication");
const webpack = require("webpack");
const path = require("path");
const webpackDevMiddleware = require("webpack-dev-middleware");
const storyboard_1 = require("storyboard");
const conf = path.join(__dirname, '../../config/webpack.development');
const config = require(conf);
class DevApplication extends CompactdApplication_1.CompactdApplication {
    constructor(host, port) {
        super(host, port);
        this.compiler = (~process.argv.indexOf('--no-webpack')
            || process.env.NO_WEBPACK) ? undefined : webpack(config);
    }
    configure() {
        super.configure();
        if (this.compiler) {
            const devMiddleware = webpackDevMiddleware(this.compiler, {
                noInfo: true,
                publicPath: '/',
                stats: {
                    colors: true
                },
                log: (data) => {
                    storyboard_1.mainStory.info('webpack', data);
                }
            });
            this.app.use(devMiddleware);
            this.app.get('*', (req, res, next) => {
                if (!req.url.startsWith('/database') && !req.url.startsWith('/api')) {
                    var filename = path.join(this.compiler.outputPath, 'index.html');
                    //  See https://github.com/jantimon/html-webpack-plugin/issues/145#issuecomment-312911903
                    devMiddleware.waitUntilValid(() => {
                        this.compiler.outputFileSystem.readFile(filename, (err, result) => {
                            if (err) {
                                return next(err);
                            }
                            res.set('content-type', 'text/html');
                            res.send(result);
                            res.end();
                        });
                    });
                    return;
                }
                next();
            });
            this.app.use((require("webpack-hot-middleware"))(this.compiler, {
                log: storyboard_1.mainStory.info.bind(storyboard_1.mainStory.info.prototype, 'hmr')
            }));
        }
    }
    route() {
        super.route();
        this.app.all('/api/*', function (req, res) {
            res.status(404).send({ error: 'This is not the endpoint you are looking for' });
        });
    }
}
exports.DevApplication = DevApplication;
//# sourceMappingURL=DevApplication.js.map