"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.KafkaService = void 0;
var uid_1 = require("uid");
var fs = require("fs");
var path = require("path");
var moment = require("moment");
var ssh_service_1 = require("./ssh.service");
var Kafka = require('kafkajs').Kafka;
var clients = {};
var USER_HOME = process.env.HOME || process.env.USERPROFILE;
var yunserFolder = path.resolve(USER_HOME, '.yunser'); // TODO package，npm install cmd-core
if (!fs.existsSync(yunserFolder)) {
    // console.log('创建目录')
    fs.mkdirSync(yunserFolder);
}
var appFolder = path.resolve(yunserFolder, 'dms-cli'); // TODO package，npm install cmd-core
if (!fs.existsSync(appFolder)) {
    fs.mkdirSync(appFolder);
}
var redisConnectionFilePath = path.resolve(appFolder, 'kafka.connection.json');
if (!fs.existsSync(redisConnectionFilePath)) {
    fs.writeFileSync(redisConnectionFilePath, '[]', 'utf8');
}
function loadJson(path, defaultValue) {
    if (defaultValue === void 0) { defaultValue = null; }
    return __awaiter(this, void 0, void 0, function () {
        var content;
        return __generator(this, function (_a) {
            content = fs.readFileSync(path, 'utf-8');
            // console.log('content', content)
            if (content) {
                return [2 /*return*/, JSON.parse(content)];
            }
            return [2 /*return*/, defaultValue];
        });
    });
}
var g_kafka;
var g_kafka_admin;
var g_kafka_consumer;
var g_kafka_producer;
var KafkaService = /** @class */ (function () {
    function KafkaService() {
    }
    KafkaService.prototype.index = function (_body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, 'kafka home'];
            });
        });
    };
    KafkaService.prototype.init = function (_body) {
        return __awaiter(this, void 0, void 0, function () {
            var list, item, host, port, kafka, admin, groupId, consumer, producer;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, loadJson(redisConnectionFilePath, [])];
                    case 1:
                        list = _a.sent();
                        item = list[0];
                        host = item.host, port = item.port;
                        kafka = new Kafka({
                            clientId: 'dms-client-01',
                            brokers: [
                                "".concat(host, ":").concat(port),
                            ],
                        });
                        g_kafka = kafka;
                        admin = kafka.admin();
                        g_kafka_admin = admin;
                        return [4 /*yield*/, admin.connect()];
                    case 2:
                        _a.sent();
                        groupId = 'dms-group-01';
                        // const groupId = 'test-group-1676797911024'
                        console.log('consumer/groupId', groupId);
                        consumer = kafka.consumer({
                            groupId: groupId,
                        });
                        g_kafka_consumer = consumer;
                        return [4 /*yield*/, consumer.connect()];
                    case 3:
                        _a.sent();
                        producer = kafka.producer();
                        g_kafka_producer = producer;
                        return [4 /*yield*/, producer.connect()];
                    case 4:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    KafkaService.prototype.topics = function (_body) {
        return __awaiter(this, void 0, void 0, function () {
            var topics;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, g_kafka_admin.listTopics()];
                    case 1:
                        topics = _a.sent();
                        return [2 /*return*/, {
                                list: topics.map(function (item) {
                                    return {
                                        name: item,
                                    };
                                }),
                            }];
                }
            });
        });
    };
    KafkaService.prototype.groups = function (_body) {
        return __awaiter(this, void 0, void 0, function () {
            var groups;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, g_kafka_admin.listGroups()];
                    case 1:
                        groups = (_a.sent()).groups;
                        return [2 /*return*/, {
                                list: groups,
                            }];
                }
            });
        });
    };
    KafkaService.prototype.groupDetail = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var groupId, topics, topic2OffsetMap, _i, topics_1, topic, topicOffsets, offsets;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        groupId = body.groupId;
                        return [4 /*yield*/, g_kafka_admin.listTopics()
                            // const { groups } = await g_kafka_admin.listGroups()
                        ];
                    case 1:
                        topics = _a.sent();
                        topic2OffsetMap = {};
                        _i = 0, topics_1 = topics;
                        _a.label = 2;
                    case 2:
                        if (!(_i < topics_1.length)) return [3 /*break*/, 5];
                        topic = topics_1[_i];
                        return [4 /*yield*/, g_kafka_admin.fetchTopicOffsets(topic)
                            // [ { partition: 0, offset: '21', high: '21', low: '0' } ]
                            // console.log('topicOffsets', topicOffsets)
                            // topic.offsets = topicOffsets
                        ];
                    case 3:
                        topicOffsets = _a.sent();
                        // [ { partition: 0, offset: '21', high: '21', low: '0' } ]
                        // console.log('topicOffsets', topicOffsets)
                        // topic.offsets = topicOffsets
                        topic2OffsetMap[topic] = topicOffsets;
                        _a.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5: return [4 /*yield*/, g_kafka_admin.fetchOffsets({
                            groupId: groupId,
                            topics: topics,
                            // resolveOffsets: true,
                        })
                        // [
                        //     {
                        //         "topic": "mac-topic-test",
                        //         "partitions": [
                        //             {
                        //                 "partition": 0,
                        //                 "offset": "19",
                        //                 "metadata": null
                        //             }
                        //         ]
                        //     }
                        // ]
                    ];
                    case 6:
                        offsets = _a.sent();
                        // [
                        //     {
                        //         "topic": "mac-topic-test",
                        //         "partitions": [
                        //             {
                        //                 "partition": 0,
                        //                 "offset": "19",
                        //                 "metadata": null
                        //             }
                        //         ]
                        //     }
                        // ]
                        return [2 /*return*/, {
                                offsets: offsets.map(function (offset) {
                                    var topicOffsets = topic2OffsetMap[offset.topic];
                                    var partitions = offset.partitions.filter(function (item) { return item.offset != -1; });
                                    partitions.forEach(function (item) {
                                        var partition = item.partition;
                                        var fOs = topicOffsets.find(function (_item) { return _item.partition == partition; });
                                        if (fOs) {
                                            item.topicOffset = parseInt(fOs.offset);
                                        }
                                        else {
                                            item.topicOffset = -1;
                                        }
                                    });
                                    if (partitions.length == 0) {
                                        return null;
                                    }
                                    return __assign(__assign({}, offset), { partitions: partitions });
                                }).filter(function (item) { return item; }),
                                // list: groups,
                            }];
                }
            });
        });
    };
    KafkaService.prototype.send = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var topic, content, res;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        topic = body.topic, content = body.content;
                        return [4 /*yield*/, g_kafka_producer.send({
                                // topic: 'ntopic-test',
                                // topic: 'mac-topic-test',
                                topic: topic,
                                messages: [
                                    {
                                        value: content,
                                    },
                                ],
                            })
                            // console.log('res', res)
                        ];
                    case 1:
                        res = _a.sent();
                        // console.log('res', res)
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    KafkaService.prototype.subscribe = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var webSocketId, topic;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        webSocketId = body.webSocketId, topic = body.topic;
                        return [4 /*yield*/, g_kafka_consumer.subscribe({
                                // topic: 'test-topic', 
                                // topic: /ntopic-.*/i, 
                                // topic: 'mac-topic-test',
                                topic: topic,
                                // fromBeginning: true
                            })
                            // console.log('consumer/subscribed')
                        ];
                    case 1:
                        _a.sent();
                        // console.log('consumer/subscribed')
                        return [4 /*yield*/, g_kafka_consumer.run({
                                eachMessage: function (_a) {
                                    var topic = _a.topic, partition = _a.partition, message = _a.message;
                                    return __awaiter(_this, void 0, void 0, function () {
                                        var msg, time;
                                        return __generator(this, function (_b) {
                                            msg = message.value.toString();
                                            console.log('consumer/eachMessage', topic, partition, msg);
                                            time = moment().format('YYYY-MM-DD HH:mm:ss');
                                            (0, ssh_service_1.sendTcpMsg)({
                                                webSocketId: webSocketId,
                                                message: {
                                                    id: (0, uid_1.uid)(8),
                                                    time: time,
                                                    type: 'message',
                                                    data: {
                                                        type: 'message',
                                                        topic: topic,
                                                        partition: partition,
                                                        content: msg,
                                                    }
                                                }
                                            });
                                            return [2 /*return*/];
                                        });
                                    });
                                },
                            })];
                    case 2:
                        // console.log('consumer/subscribed')
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    KafkaService.prototype.removeTopic = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var topic;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        topic = body.topic;
                        return [4 /*yield*/, g_kafka_admin.deleteTopics({
                                topics: [topic],
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    KafkaService.prototype.removeGroup = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var groupId;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        groupId = body.groupId;
                        return [4 /*yield*/, g_kafka_admin.deleteGroups([groupId])];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    return KafkaService;
}());
exports.KafkaService = KafkaService;
//# sourceMappingURL=kafka.service.js.map