"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChangesWebservice = void 0;
var bfast_1 = require("bfast");
var ChangesWebservice = (function () {
    function ChangesWebservice() {
    }
    ChangesWebservice.prototype.changesV2 = function (config, prefix, databaseController, securityController, databaseAdapter) {
        if (prefix === void 0) { prefix = '/'; }
        return bfast_1.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, databaseAdapter, securityController, 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 ChangesWebservice;
}());
exports.ChangesWebservice = ChangesWebservice;
