"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = void 0;
const descriptor_1 = require("./descriptor");
const services = __importStar(require("./reflection_grpc_pb"));
const reflection_pb_1 = require("./reflection_pb");
const descriptor_2 = require("protobufjs/ext/descriptor");
const lodash_set_1 = __importDefault(require("lodash.set"));
class Client {
    constructor(url, credentials, options) {
        this.grpcClient = new services.ServerReflectionClient(url, credentials, options);
    }
    listServices() {
        return new Promise((resolve, reject) => {
            function dataCallback(response) {
                var _a;
                if (response.hasListServicesResponse()) {
                    const services = (_a = response
                        .getListServicesResponse()) === null || _a === void 0 ? void 0 : _a.getServiceList().map(svc => {
                        return svc.getName();
                    });
                    resolve(services);
                }
                else {
                    reject(Error());
                }
            }
            function errorCallback(e) {
                reject(e);
            }
            const request = new reflection_pb_1.ServerReflectionRequest();
            request.setListServices('*');
            const grpcCall = this.grpcClient.serverReflectionInfo({});
            grpcCall.on('data', dataCallback);
            grpcCall.on('error', errorCallback);
            grpcCall.write(request);
            grpcCall.end();
        });
    }
    fileContainingSymbol(symbol) {
        return new Promise((resolve, reject) => {
            this.getFileContainingSymbol(symbol)
                .then(val => resolve(this.resolveFileDescriptorSet(val)))
                .catch(err => reject(err));
        });
    }
    fileByFilename(filename) {
        return new Promise((resolve, reject) => {
            this.getFileByFilename(filename)
                .then(val => resolve(this.resolveFileDescriptorSet(val)))
                .catch(err => reject(err));
        });
    }
    async resolveFileDescriptorSet(fileDescriptorProtoBytes) {
        const fileDescriptorSet = descriptor_2.FileDescriptorSet.create();
        const fileDescriptorProtos = await this.resolveDescriptorRecursive(fileDescriptorProtoBytes);
        lodash_set_1.default(fileDescriptorSet, 'file', Array.from(fileDescriptorProtos.values()));
        return descriptor_1.getDescriptorRootFromDescriptorSet(fileDescriptorSet);
    }
    async resolveDescriptorRecursive(fileDescriptorProtoBytes) {
        let fileDescriptorProtos = new Map();
        for (const descriptorByte of fileDescriptorProtoBytes) {
            const fileDescriptorProto = descriptor_2.FileDescriptorProto.decode(descriptorByte);
            if (fileDescriptorProto.dependency) {
                const dependencies = fileDescriptorProto.dependency;
                for (const dep of dependencies) {
                    const depProtoBytes = await this.getFileByFilename(dep);
                    const protoDependencies = await this.resolveDescriptorRecursive(depProtoBytes);
                    fileDescriptorProtos = new Map([
                        ...fileDescriptorProtos,
                        ...protoDependencies,
                    ]);
                }
            }
            if (!fileDescriptorProtos.has(fileDescriptorProto.name)) {
                fileDescriptorProtos.set(fileDescriptorProto.name, fileDescriptorProto);
            }
        }
        return fileDescriptorProtos;
    }
    getFileContainingSymbol(symbol) {
        return new Promise((resolve, reject) => {
            function dataCallback(response) {
                var _a;
                if (response.hasFileDescriptorResponse()) {
                    resolve((_a = response.getFileDescriptorResponse()) === null || _a === void 0 ? void 0 : _a.getFileDescriptorProtoList());
                }
                else {
                    reject(Error());
                }
            }
            function errorCallback(e) {
                reject(e);
            }
            const request = new reflection_pb_1.ServerReflectionRequest();
            request.setFileContainingSymbol(symbol);
            const grpcCall = this.grpcClient.serverReflectionInfo({});
            grpcCall.on('data', dataCallback);
            grpcCall.on('error', errorCallback);
            grpcCall.write(request);
            grpcCall.end();
        });
    }
    getFileByFilename(symbol) {
        return new Promise((resolve, reject) => {
            function dataCallback(response) {
                var _a;
                if (response.hasFileDescriptorResponse()) {
                    resolve((_a = response.getFileDescriptorResponse()) === null || _a === void 0 ? void 0 : _a.getFileDescriptorProtoList());
                }
                else {
                    reject(Error());
                }
            }
            function errorCallback(e) {
                reject(e);
            }
            const request = new reflection_pb_1.ServerReflectionRequest();
            request.setFileByFilename(symbol);
            const grpcCall = this.grpcClient.serverReflectionInfo({});
            grpcCall.on('data', dataCallback);
            grpcCall.on('error', errorCallback);
            grpcCall.write(request);
            grpcCall.end();
        });
    }
}
exports.Client = Client;
//# sourceMappingURL=client.js.map