"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RealtimeWebservice = void 0;
var bfastnode_1 = require("bfastnode");
var databaseController;
var RealtimeWebservice = (function () {
    function RealtimeWebservice(database) {
        databaseController = database;
    }
    RealtimeWebservice.prototype.changesV2 = function (config, prefix) {
        if (prefix === void 0) { prefix = '/'; }
        return bfastnode_1.BFast.functions().onEvent(prefix + "v2/__changes__", function (request, response) {
            if (request.auth.applicationId === config.applicationId) {
                var bypassDomainVerification = config.masterKey === request.auth.masterKey;
                if (request.body.pipeline && Array.isArray(request.body.pipeline) && request.body.domain) {
                    databaseController.changes(request.body.domain, request.body.pipeline, function (doc) {
                        response.emit({ change: doc });
                    }, {
                        bypassDomainVerification: bypassDomainVerification,
                        resumeToken: request.body.resumeToken
                    }).then(function (_) {
                        response.socket.on('disconnect', function (__1) {
                            try {
                                _.close();
                            }
                            catch (_12) {
                                console.log(_12);
                            }
                            console.log("INFO : changes resource released, with reason --> " + __1);
                        });
                        response.emit({ info: 'start listening for changes' });
                    }).catch(function (reason) {
                        response.emit({ error: reason.toString() });
                    });
                }
                else {
                    response.emit({ error: 'pipeline/domain is required' });
                }
            }
            else {
                response.emit({ error: 'unauthorized' });
            }
        });
    };
    return RealtimeWebservice;
}());
exports.RealtimeWebservice = RealtimeWebservice;
