import * as $protobuf from "protobufjs";
import { jsonToHump } from './util/convert';
export function rpcCallHook(method, requestCtor, responseCtor, request, callback) {
    if (!request)
        throw TypeError("request must be specified");
    var self = this;
    if (!callback)
        return $protobuf.util.asPromise(rpcCallHook, self, method, requestCtor, responseCtor, request);
    if (!self.rpcImpl) {
        setTimeout(function () { callback(Error("already ended")); }, 0);
        return undefined;
    }
    try {
        request = requestCtor.toObject(request);
        return self.rpcImpl(method, request, function rpcCallback(err, response) {
            if (err) {
                self.emit("error", err, method);
                return callback(err);
            }
            if (response === null) {
                self.end(true);
                return undefined;
            }
            jsonToHump(response);
            response = responseCtor.fromObject(response);
            self.emit("data", response, method);
            return callback(null, response);
        });
    }
    catch (err) {
        self.emit("error", err, method);
        setTimeout(function () { callback(err); }, 0);
        return undefined;
    }
}
