var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
export const NewHandleResult = (receipt, result, error) => {
    return { messageReceipt: receipt, result: result, error: error };
};
export class Handler {
    constructor(config) {
        this.handle = (ctx, receipt, message) => __awaiter(this, void 0, void 0, function* () {
            for (const func of this.config.functions || []) {
                const res = yield func(ctx, message);
                if (res.handled) {
                    res.messageReceipt = receipt;
                    // on handled, execute posthooks
                    if (res.error == undefined) {
                        for (const posthook of this.config.postHooks || []) {
                            // if error in posthook, inject posthook error in the result and break
                            const error = yield posthook(ctx, res);
                            if (error) {
                                res.error = error;
                                break;
                            }
                        }
                    }
                    return res;
                }
            }
            // Not handled, should return error?
            return { messageReceipt: receipt };
        });
        this.registerFunction = (func) => {
            this.config.functions.push(func);
        };
        this.config = config;
    }
}
export class HandlerFactory {
    constructor(config) {
        this.config = config;
    }
    spawn() {
        return new Handler(this.config);
    }
}
//# sourceMappingURL=handler.js.map