"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const eventService_1 = require("./eventService");
/**
 * Enables you to track the completion of transactions triggered by Arc.js functions.
 * You can subscribe to events that tell you how many transactions are anticipated when
 * the transactions have completed.  For more information, see [subscribe](TransactionService#subscribe).
 */
class TransactionService extends eventService_1.EventService {
    /**
     * Generate a new invocation key for the given topic and function.
     * Topic should look like "[classname][functionname]".
     * @param topic
     */
    static generateInvocationKey(topic) {
        return Symbol(topic);
    }
    /**
     * Publish the kick-off event and return the payload that should be used for the ensuing
     * events that will carry an actual tx in the payload for the invoked function.
     * `invocationKey` is a unique key for the returned payload that can be used for scoping
     * the events.
     * @param topic
     * @param options
     * @param txCount
     * @param suppressKickOff
     */
    static publishKickoffEvent(topic, options, txCount, suppressKickOff = false) {
        const payload = {
            invocationKey: TransactionService.generateInvocationKey(topic),
            options,
            tx: null,
            txCount,
        };
        if (!suppressKickOff) {
            /**
             * publish the "kick-off" event
             */
            TransactionService.publishTxEvent(topic, payload);
        }
        return payload;
    }
    /**
     * Send the given payload to subscribers of the given topic.
     *
     * @param topic See [subscribe](EventService#subscribe)
     * @param payload Sent in the subscription callback.
     * @param tx the transaction.  Don't supply for kick-off event.
     * @returns True if there are any subscribers
     */
    static publishTxEvent(topic, payload, tx) {
        if (tx) {
            payload = Object.assign({}, payload, { tx });
        }
        return eventService_1.EventService.publish(topic, payload);
    }
    /**
     * Subscribe to all given topics and resend as the given supertopic with superPayload.
     * @param topics topics or topic
     * @param superTopic topic to resend as
     * @param superPayload payload to send
     * @returns An interface with `.unsubscribe()`.  Be sure to call it!
     */
    static resendTxEvents(topics, superTopic, superPayload) {
        return eventService_1.EventService.subscribe(topics, (topic, txEventInfo) => {
            if (txEventInfo.tx) { // skip kick-off events
                TransactionService.publishTxEvent(superTopic, superPayload, txEventInfo.tx);
            }
        });
    }
}
exports.TransactionService = TransactionService;
//# sourceMappingURL=transactionService.js.map