"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const proto_loader_1 = require("@grpc/proto-loader");
const grpc_1 = require("grpc");
class GRPCClient {
    constructor(protoPath, packageName, service, host, options = {}, tls = false) {
        this.packageDefinition = proto_loader_1.loadSync(protoPath, {
            defaults: options.defaults === undefined ? true : options.defaults,
            enums: options.enums === undefined ? String : options.enums,
            keepCase: options.keepCase === undefined ? true : options.keepCase,
            longs: options.longs === undefined ? String : options.longs,
            oneofs: options.oneofs === undefined ? true : options.oneofs,
        });
        const proto = grpc_1.loadPackageDefinition(this.packageDefinition)[packageName];
        const listMethods = this.packageDefinition[`${packageName}.${service}`];
        const channelCredentials = tls
            ? grpc_1.credentials.createSsl()
            : grpc_1.credentials.createInsecure();
        this.client = new proto[service](host, channelCredentials);
        this.listNameMethods = [];
        for (const key in listMethods) {
            if (listMethods[key]) {
                const methodName = listMethods[key].originalName;
                this.listNameMethods.push(methodName);
                this[`${methodName}Async`] = (data, fnAnswer) => {
                    this.client[methodName](data, fnAnswer);
                };
                this[`${methodName}Stream`] = data => {
                    return this.client[methodName](data);
                };
                this[`${methodName}Sync`] = data => {
                    const client = this.client;
                    return new Promise((resolve, reject) => {
                        client[methodName](data, (err, dat) => {
                            if (err) {
                                return reject(err);
                            }
                            resolve(dat);
                        });
                    });
                };
            }
        }
    }
    runService(fnName, data, fnAnswer) {
        this.client[fnName](data, fnAnswer);
    }
    listMethods() {
        return this.listNameMethods;
    }
}
exports.GRPCClient = GRPCClient;
//# sourceMappingURL=GRPCClient.js.map