"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var express = require("express");
var http = require("http");
var path = require("path");
var find_package_dir_1 = require("./find-package-dir");
/**
 * Web-server component. Serves the chart interative chart.
 */
var WebServer = /** @class */ (function () {
    function WebServer(portNo) {
        /**
         * The Express server instance that implements the web-server.
         */
        this.server = null;
        /**
         * The data that defines the chart.
         * Passed to the browser-based chart via REST API.
         */
        this.chartDef = {};
        this.requestedPortNo = portNo;
        this.assignedPortNo = portNo;
    }
    /**
     * Get the URL to access the web-sever.
     */
    WebServer.prototype.getUrl = function () {
        return "http://127.0.0.1:" + this.assignedPortNo;
    };
    /**
     * Start the web-server.
     */
    WebServer.prototype.start = function () {
        var _this = this;
        return find_package_dir_1.findPackageDir(__dirname)
            .then(function (parentDir) {
            return new Promise(function (resolve, reject) {
                var app = express();
                _this.server = http.createServer(app);
                var staticFilesPath = path.join(parentDir, "templates/image");
                var staticFilesMiddleWare = express.static(staticFilesPath);
                app.use("/", staticFilesMiddleWare);
                app.get("/chart-data", function (request, response) {
                    response.json({
                        chartDef: _this.chartDef,
                    });
                });
                _this.server.listen(_this.requestedPortNo, function (err) {
                    if (err) {
                        reject(err);
                    }
                    else {
                        _this.assignedPortNo = _this.server.address().port;
                        resolve();
                    }
                });
            });
        });
    };
    /**
     * Stop the web-server.
     */
    /*async*/ WebServer.prototype.stop = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this.server.close(function (err) {
                _this.server = null;
                if (err) {
                    reject(err);
                    return;
                }
                resolve();
            });
        });
    };
    return WebServer;
}());
exports.WebServer = WebServer;
if (require.main === module) {
    // For command line testing.
    new WebServer(3000)
        .start()
        .then(function () {
        console.log("Server started;");
    })
        .catch(function (err) {
        console.error("Error starting web server.");
        console.error(err && err.stack || err);
    });
}
//# sourceMappingURL=web-server.js.map