"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebhookChannel2023Type = exports.isWebHook2023Channel = void 0;
const LogUtil_1 = require("../../../logging/LogUtil");
const ErrorUtil_1 = require("../../../util/errors/ErrorUtil");
const Vocabularies_1 = require("../../../util/Vocabularies");
const BaseChannelType_1 = require("../BaseChannelType");
function isWebHook2023Channel(channel) {
    return channel.type === Vocabularies_1.NOTIFY.WebHookChannel2023;
}
exports.isWebHook2023Channel = isWebHook2023Channel;
/**
 * The notification channel type WebHookChannel2023 as described in
 * https://solid.github.io/notifications/webhook-channel-2023
 *
 * Requires read permissions on a resource to be able to receive notifications.
 *
 * Also handles the `state` feature if present.
 */
class WebhookChannel2023Type extends BaseChannelType_1.BaseChannelType {
    /**
     * @param route - The route corresponding to the URL of the subscription service of this channel type.
     * @param webIdRoute - The route to the WebID that needs to be used when generating DPoP tokens for notifications.
     * @param stateHandler - The {@link StateHandler} that will be called after a successful subscription.
     * @param features - The features that need to be enabled for this channel type.
     */
    constructor(route, webIdRoute, stateHandler, features) {
        super(Vocabularies_1.NOTIFY.terms.WebHookChannel2023, route, features, [{ path: Vocabularies_1.NOTIFY.sendTo, minCount: 1, maxCount: 1 }]);
        this.logger = (0, LogUtil_1.getLoggerFor)(this);
        this.stateHandler = stateHandler;
        this.webId = webIdRoute.getPath();
    }
    async initChannel(data) {
        const subject = await this.validateSubscription(data);
        const channel = await this.quadsToChannel(data, subject);
        const sendTo = data.getObjects(subject, Vocabularies_1.NOTIFY.terms.sendTo, null)[0];
        return {
            ...channel,
            type: Vocabularies_1.NOTIFY.WebHookChannel2023,
            sendTo: sendTo.value,
        };
    }
    async toJsonLd(channel) {
        const json = await super.toJsonLd(channel);
        // Add the stored WebID as sender.
        // We don't store it in the channel object itself as we always know what it is anyway.
        json.sender = this.webId;
        return json;
    }
    async completeChannel(channel) {
        try {
            // Send the state notification, if there is one
            await this.stateHandler.handleSafe({ channel });
        }
        catch (error) {
            this.logger.error(`Error emitting state notification: ${(0, ErrorUtil_1.createErrorMessage)(error)}`);
        }
    }
}
exports.WebhookChannel2023Type = WebhookChannel2023Type;
//# sourceMappingURL=WebhookChannel2023Type.js.map