"use strict";
/**
 * Copyright © 2018 Emu Analytics
 */
Object.defineProperty(exports, "__esModule", { value: true });
const http = require("http");
const utils_1 = require("../utils");
const app_1 = require("./app");
class StyleServer {
    /**
     *
     * @param client Flo.w engine client
     * @param style Mapbox style
     * @param styleId Style ID to update on save (can be null for read-only)
     */
    constructor(client, style, writeable) {
        this.port = this.normalizePort(process.env.PORT || '8000');
        app_1.app.set('port', this.port);
        app_1.app.set('style', style);
        app_1.app.set('writeable', writeable);
        app_1.app.set('client', client);
        this.server = http.createServer(app_1.app);
        this.server.listen(this.port);
        this.server.on('error', this.onError.bind(this));
        this.server.on('listening', this.onListening.bind(this));
    }
    normalizePort(val) {
        const portNum = parseInt(val, 10);
        if (isNaN(portNum)) {
            // named pipe
            return val;
        }
        if (portNum >= 0) {
            // port number
            return portNum;
        }
        return false;
    }
    onError(error) {
        if (error.syscall !== 'listen') {
            throw error;
        }
        const bind = typeof this.port === 'string' ? `Pipe ${this.port}` : `Port ${this.port}`;
        // handle specific listen errors with friendly messages
        switch (error.code) {
            case 'EACCES':
                utils_1.logError(`${bind} requires elevated privileges`);
                process.exit(1);
                break;
            case 'EADDRINUSE':
                utils_1.logError(`${bind} is already in use`);
                process.exit(1);
                break;
            default:
                throw error;
        }
    }
    /**
     * Event listener for HTTP server "listening" event.
     */
    onListening() {
        const address = this.server.address();
        const bind = typeof address === 'string' ? `pipe ${address}` : `port ${address.port}`;
        utils_1.logDetail(`Style server listening on port ${this.port}`);
        utils_1.logInfo(`:rocket: Point your browser at http://localhost:${this.port}`);
        this.postListen();
    }
    postListen() {
        return Promise.resolve(null);
    }
}
exports.StyleServer = StyleServer;
//# sourceMappingURL=index.js.map