"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const firebase = require("firebase-admin");
const _ = require("lodash");
const config_1 = require("./config");
function apps() {
    if (typeof apps.singleton === 'undefined') {
        apps.init();
    }
    return apps.singleton;
}
exports.apps = apps;
(function (apps) {
    /** @hidden */
    apps.garbageCollectionInterval = 2 * 60 * 1000;
    /** @hidden */
    function delay(delay) {
        return new Promise((resolve) => {
            setTimeout(resolve, delay);
        });
    }
    apps.delay = delay;
    apps.init = () => (apps.singleton = new Apps());
    class Apps {
        constructor() {
            this._refCounter = {};
        }
        _appAlive(appName) {
            try {
                const app = firebase.app(appName);
                return !_.get(app, 'isDeleted_');
            }
            catch (e) {
                return false;
            }
        }
        _destroyApp(appName) {
            if (!this._appAlive(appName)) {
                return;
            }
            firebase
                .app(appName)
                .delete()
                .catch(_.noop);
        }
        retain() {
            const increment = (n) => {
                return (n || 0) + 1;
            };
            // Increment counter for admin because function might use event.data.ref
            _.update(this._refCounter, '__admin__', increment);
        }
        release() {
            const decrement = (n) => {
                return n - 1;
            };
            return delay(apps.garbageCollectionInterval).then(() => {
                _.update(this._refCounter, '__admin__', decrement);
                _.forEach(this._refCounter, (count, key) => {
                    if (count <= 0) {
                        this._destroyApp(key);
                    }
                });
            });
        }
        get admin() {
            if (this._emulatedAdminApp) {
                return this._emulatedAdminApp;
            }
            if (this._appAlive('__admin__')) {
                return firebase.app('__admin__');
            }
            return firebase.initializeApp(this.firebaseArgs, '__admin__');
        }
        /**
         * This function allows the Firebase Emulator Suite to override the FirebaseApp instance
         * used by the Firebase Functions SDK. Developers should never call this function for
         * other purposes.
         */
        setEmulatedAdminApp(app) {
            this._emulatedAdminApp = app;
        }
        get firebaseArgs() {
            return _.assign({}, config_1.firebaseConfig(), {
                credential: firebase.credential.applicationDefault(),
            });
        }
    }
    apps.Apps = Apps;
})(apps = exports.apps || (exports.apps = {}));
