"use strict";
/*
 * Copyright 2017 Teppo Kurki <teppo.kurki@iki.fi>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const debug = require('debug')('signalk:interfaces:webapps');
const fs = require('fs');
const path = require('path');
const express = require('express');
const modulesWithKeyword = require('../modules').modulesWithKeyword;
const constants_1 = require("../constants");
const lodash_1 = require("lodash");
module.exports = function (app) {
    return {
        start: function () {
            app.webapps = mountWebModules(app, 'signalk-webapp').map(moduleData => moduleData.metadata);
            app.addons = mountWebModules(app, 'signalk-node-server-addon').map(moduleData => moduleData.metadata);
            app.embeddablewebapps = mountWebModules(app, 'signalk-embeddable-webapp').map(moduleData => moduleData.metadata);
            app.pluginconfigurators = mountWebModules(app, 'signalk-plugin-configurator').map(moduleData => moduleData.metadata);
            mountApis(app);
        },
        // tslint:disable-next-line: no-empty
        stop: function () { }
    };
};
function mountWebModules(app, keyword) {
    debug(`mountWebModules:${keyword}`);
    const modules = modulesWithKeyword(app, keyword);
    modules.forEach(moduleData => {
        let webappPath = path.join(moduleData.location, moduleData.module);
        if (fs.existsSync(webappPath + '/public/')) {
            webappPath += '/public/';
        }
        debug('Mounting web module /' + moduleData.module + ':' + webappPath);
        app.use('/' + moduleData.module, express.static(webappPath));
    });
    return modules;
}
function mountApis(app) {
    app.get(`${constants_1.SERVERROUTESPREFIX}/webapps`, function (req, res) {
        const allWebapps = [].concat(app.webapps).concat(app.embeddablewebapps);
        res.json(lodash_1.uniqBy(allWebapps, 'name'));
    });
    app.get(`${constants_1.SERVERROUTESPREFIX}/addons`, function (req, res) {
        res.json(app.addons);
    });
}
