"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 });
var _ = require("lodash");
var firebase = require("firebase-admin");
var index_1 = require("./index");
var sha1 = require("sha1");
/** @internal */
function apps() {
    if (typeof apps.singleton === 'undefined') {
        apps.init(index_1.config());
    }
    return apps.singleton;
}
exports.apps = apps;
/** @internal */
(function (apps) {
    /** @internal */
    apps.garbageCollectionInterval = 2 * 60 * 1000;
    /** @internal */
    function delay(delay) {
        return new Promise(function (resolve) {
            setTimeout(resolve, delay);
        });
    }
    apps.delay = delay;
    apps.init = function (config) { return apps.singleton = new Apps(config); };
    /** @internal */
    var Apps = (function () {
        function Apps(config) {
            this._config = config;
            this._refCounter = {};
        }
        Apps.prototype._appAlive = function (appName) {
            try {
                var app = firebase.app(appName);
                return !_.get(app, 'isDeleted_');
            }
            catch (e) {
                return false;
            }
        };
        Apps.prototype._appName = function (auth) {
            if (!auth || typeof auth !== 'object') {
                return '__noauth__';
            }
            else if (auth.admin) {
                return '__admin__';
            }
            else if (!auth.variable) {
                return '__noauth__';
            }
            else {
                // Use hash of auth variable as name of user-authenticated app
                return sha1(JSON.stringify(auth.variable));
            }
        };
        Apps.prototype._destroyApp = function (appName) {
            if (!this._appAlive(appName)) {
                return;
            }
            firebase.app(appName).delete().catch(_.noop);
        };
        Apps.prototype.retain = function (payload) {
            var auth = _.get(payload, 'auth', null);
            var increment = function (n) {
                return (n || 0) + 1;
            };
            // Increment counter for admin because function might use event.data.adminRef
            _.update(this._refCounter, '__admin__', increment);
            // Increment counter according to auth type because function might use event.data.ref
            _.update(this._refCounter, this._appName(auth), increment);
        };
        Apps.prototype.release = function (payload) {
            var _this = this;
            var auth = _.get(payload, 'auth', null);
            var decrement = function (n) {
                return n - 1;
            };
            return delay(apps.garbageCollectionInterval).then(function () {
                _.update(_this._refCounter, '__admin__', decrement);
                _.update(_this._refCounter, _this._appName(auth), decrement);
                _.forEach(_this._refCounter, function (count, key) {
                    if (count <= 0) {
                        _this._destroyApp(key);
                    }
                });
            });
        };
        Object.defineProperty(Apps.prototype, "admin", {
            get: function () {
                if (this._appAlive('__admin__')) {
                    return firebase.app('__admin__');
                }
                return firebase.initializeApp(this.firebaseArgs, '__admin__');
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Apps.prototype, "noauth", {
            get: function () {
                if (this._appAlive('__noauth__')) {
                    return firebase.app('__noauth__');
                }
                var param = _.extend({}, this.firebaseArgs, {
                    databaseAuthVariableOverride: null,
                });
                return firebase.initializeApp(param, '__noauth__');
            },
            enumerable: true,
            configurable: true
        });
        Apps.prototype.forMode = function (auth) {
            if (typeof auth !== 'object') {
                return this.noauth;
            }
            if (auth.admin) {
                return this.admin;
            }
            if (!auth.variable) {
                return this.noauth;
            }
            var appName = this._appName(auth);
            if (this._appAlive(appName)) {
                return firebase.app(appName);
            }
            var param = _.extend({}, this.firebaseArgs, {
                databaseAuthVariableOverride: auth.variable,
            });
            return firebase.initializeApp(param, appName);
        };
        Object.defineProperty(Apps.prototype, "firebaseArgs", {
            get: function () {
                return _.get(this._config, 'firebase', {});
            },
            enumerable: true,
            configurable: true
        });
        return Apps;
    }());
    apps.Apps = Apps;
})(apps = exports.apps || (exports.apps = {}));
