"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.MongoService = void 0;
var fs = require("fs");
var path = require("path");
var nodePath = path;
var uid_1 = require("uid");
var mongodb_1 = require("mongodb");
var g_connections = {};
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 collectionDbFilePath = path.resolve(appFolder, 'file.collection.json');
if (!fs.existsSync(collectionDbFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    fs.writeFileSync(collectionDbFilePath, '[]', 'utf8');
}
var mongoDefault = {
    version: '1.0.0',
    connections: [],
};
var mongoDbFilePath = path.resolve(appFolder, 'mongo.json');
if (!fs.existsSync(mongoDbFilePath)) {
    // console.log('创建目录')
    // fs.mkdirSync(yunserFolder)
    fs.writeFileSync(mongoDbFilePath, JSON.stringify(mongoDefault, null, 4), 'utf8');
}
var MongoService = /** @class */ (function () {
    function MongoService() {
    }
    MongoService.prototype.home = function (_body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, 'mongo home'];
            });
        });
    };
    MongoService.prototype.connectionList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, list;
            return __generator(this, function (_a) {
                content = fs.readFileSync(mongoDbFilePath, 'utf-8');
                list = JSON.parse(content).connections;
                return [2 /*return*/, {
                        list: list,
                    }];
            });
        });
    };
    MongoService.prototype.connectionCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var name, host, port, password, username, content, storeData;
            return __generator(this, function (_a) {
                name = body.name, host = body.host, port = body.port, password = body.password, username = body.username;
                content = fs.readFileSync(mongoDbFilePath, 'utf-8');
                storeData = JSON.parse(content);
                storeData.connections.push({
                    id: (0, uid_1.uid)(32),
                    name: name,
                    host: host,
                    port: port,
                    password: password,
                    username: username,
                });
                fs.writeFileSync(mongoDbFilePath, JSON.stringify(storeData, null, 4), 'utf-8');
                return [2 /*return*/];
            });
        });
    };
    MongoService.prototype.connectionUpdate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, data, content, storeData, idx;
            return __generator(this, function (_a) {
                id = body.id, data = body.data;
                content = fs.readFileSync(mongoDbFilePath, 'utf-8');
                storeData = JSON.parse(content);
                idx = storeData.connections.findIndex(function (_item) { return _item.id == id; });
                storeData.connections[idx] = __assign(__assign({}, storeData.connections[idx]), data);
                fs.writeFileSync(mongoDbFilePath, JSON.stringify(storeData, null, 4), 'utf-8');
                return [2 /*return*/];
            });
        });
    };
    MongoService.prototype.connectionDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, content, storeData;
            return __generator(this, function (_a) {
                id = body.id;
                content = fs.readFileSync(mongoDbFilePath, 'utf-8');
                storeData = JSON.parse(content);
                storeData.connections = storeData.connections.filter(function (item) { return item.id != id; });
                fs.writeFileSync(mongoDbFilePath, JSON.stringify(storeData, null, 4), 'utf-8');
                return [2 /*return*/];
            });
        });
    };
    MongoService.prototype.connect = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, host, port, username, password, db, _a, test, url, client;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        connectionId = (0, uid_1.uid)(32);
                        host = config.host, port = config.port, username = config.username, password = config.password, db = config.db, _a = config.test, test = _a === void 0 ? false : _a;
                        url = "mongodb://".concat(username, ":").concat(password, "@").concat(host, ":").concat(port);
                        client = new mongodb_1.MongoClient(url);
                        return [4 /*yield*/, client.connect()];
                    case 1:
                        _b.sent();
                        if (test) {
                            return [2 /*return*/, {}];
                        }
                        g_connections[connectionId] = {
                            client: client,
                            config: config,
                        };
                        return [2 /*return*/, {
                                connectionId: connectionId,
                            }];
                }
            });
        });
    };
    MongoService.prototype.databases = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var client, admin, dbInfo;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        admin = client.db().admin();
                        return [4 /*yield*/, admin.listDatabases()];
                    case 2:
                        dbInfo = _a.sent();
                        return [2 /*return*/, {
                                list: dbInfo.databases,
                                dbInfo: dbInfo,
                            }];
                }
            });
        });
    };
    MongoService.prototype.databaseCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, client, db;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        db.createCollection('new_collection');
                        // const collections = await db.listCollections().toArray()
                        // console.log('dbInfo', dbInfo)
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.databaseDrop = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, client, db;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        return [4 /*yield*/, client.db(database).dropDatabase()];
                    case 2:
                        db = _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.collections = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, client, db, collections;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        return [4 /*yield*/, db.listCollections().toArray()
                            // console.log('dbInfo', dbInfo)
                        ];
                    case 2:
                        collections = _a.sent();
                        // console.log('dbInfo', dbInfo)
                        return [2 /*return*/, {
                                list: collections,
                            }];
                }
            });
        });
    };
    MongoService.prototype.collectionCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, client, db;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        console.log('collection', collection);
                        db.createCollection(collection);
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.collectionDrop = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, client, db, col;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        return [4 /*yield*/, col.drop()];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.collectionClear = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, client, db, col;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        return [4 /*yield*/, col.deleteMany({})];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.documents = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, _a, skip, _b, limit, _c, conditions, client, db, col, documents, count;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        database = body.database, collection = body.collection, _a = body.skip, skip = _a === void 0 ? 0 : _a, _b = body.limit, limit = _b === void 0 ? 1000 : _b, _c = body.conditions, conditions = _c === void 0 ? {} : _c;
                        console.log('conditions', conditions);
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _d.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        if (conditions['_id']) {
                            conditions['_id'] = new mongodb_1.ObjectId(conditions['_id']);
                        }
                        return [4 /*yield*/, col.find(conditions, {
                                limit: limit,
                                skip: skip,
                            }).toArray()];
                    case 2:
                        documents = _d.sent();
                        console.log('documents', documents);
                        return [4 /*yield*/, col.countDocuments(conditions)];
                    case 3:
                        count = _d.sent();
                        return [2 /*return*/, {
                                total: count,
                                list: documents,
                            }];
                }
            });
        });
    };
    MongoService.prototype.documentCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, data, client, db, col, saveData, objId, ret;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection, data = body.data;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        saveData = __assign({}, data);
                        if (saveData._id) {
                            objId = ('' + saveData._id).padStart(24, '0').slice(0, 24);
                            console.log('objId', objId);
                            saveData._id = new mongodb_1.ObjectId(objId);
                        }
                        return [4 /*yield*/, col.insertOne(saveData)];
                    case 2:
                        ret = _a.sent();
                        console.log('ret', ret);
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.documentUpdate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, id, data, client, db, col, ret;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection, id = body.id, data = body.data;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        return [4 /*yield*/, col.findOneAndReplace({
                                _id: new mongodb_1.ObjectId(id),
                            }, data)];
                    case 2:
                        ret = _a.sent();
                        console.log('ret', ret);
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.documentUpdateByQuery = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, query, data, client, db, col, ret;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection, query = body.query, data = body.data;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        return [4 /*yield*/, col.updateMany(query, {
                                $set: data,
                            })];
                    case 2:
                        ret = _a.sent();
                        console.log('ret', ret);
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.documentRemoveByQuery = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, query, data, client, db, col, ret;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection, query = body.query, data = body.data;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        return [4 /*yield*/, col.deleteMany(query)];
                    case 2:
                        ret = _a.sent();
                        console.log('ret', ret);
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.documentRemove = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, id, _a, ids, client, db, col, _i, ids_1, id_1, ret;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        database = body.database, collection = body.collection, id = body.id, _a = body.ids, ids = _a === void 0 ? [] : _a;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _b.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        if (!ids.length) return [3 /*break*/, 6];
                        _i = 0, ids_1 = ids;
                        _b.label = 2;
                    case 2:
                        if (!(_i < ids_1.length)) return [3 /*break*/, 5];
                        id_1 = ids_1[_i];
                        return [4 /*yield*/, col.deleteOne({
                                _id: new mongodb_1.ObjectId(id_1),
                            })];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 8];
                    case 6: return [4 /*yield*/, col.deleteOne({
                            _id: new mongodb_1.ObjectId(id),
                        })];
                    case 7:
                        ret = _b.sent();
                        console.log('ret', ret);
                        _b.label = 8;
                    case 8: return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype.indexList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, id, client, db, col, ret;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection, id = body.id;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        return [4 /*yield*/, col.indexes()];
                    case 2:
                        ret = _a.sent();
                        console.log('ret', ret);
                        return [2 /*return*/, {
                                list: ret,
                            }];
                }
            });
        });
    };
    MongoService.prototype.indexCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, id, client, db, col;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection, id = body.id;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db(database);
                        col = db.collection(collection);
                        // var obj_id = BSON.ObjectID.createFromHexString(id);
                        return [4 /*yield*/, col.createIndex({
                                'account': 1,
                            })
                            // console.log('ret', ret)
                        ];
                    case 2:
                        // var obj_id = BSON.ObjectID.createFromHexString(id);
                        _a.sent();
                        // console.log('ret', ret)
                        return [2 /*return*/, {
                            // list: ret,
                            }];
                }
            });
        });
    };
    MongoService.prototype.mock = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var database, collection, client, db, col, i, res;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        database = body.database, collection = body.collection;
                        return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        db = client.db('test');
                        col = db.collection('big-data-v2');
                        i = 0;
                        _a.label = 2;
                    case 2:
                        if (!(i < 1000)) return [3 /*break*/, 5];
                        return [4 /*yield*/, col.insertOne({
                                name: 'name-' + (i + 1),
                            })];
                    case 3:
                        res = _a.sent();
                        console.log('res', res);
                        _a.label = 4;
                    case 4:
                        i++;
                        return [3 /*break*/, 2];
                    case 5: return [2 /*return*/, {}];
                }
            });
        });
    };
    MongoService.prototype._getClient = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId;
            return __generator(this, function (_a) {
                connectionId = body.connectionId;
                return [2 /*return*/, g_connections[connectionId].client];
            });
        });
    };
    MongoService.prototype.serverInfo = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var client, admin, serverInfo;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._getClient(body)];
                    case 1:
                        client = _a.sent();
                        admin = client.db().admin();
                        return [4 /*yield*/, admin.serverInfo()];
                    case 2:
                        serverInfo = _a.sent();
                        console.log('serverInfo', serverInfo);
                        return [2 /*return*/, __assign({}, serverInfo)];
                }
            });
        });
    };
    return MongoService;
}());
exports.MongoService = MongoService;
//# sourceMappingURL=mongo.service.js.map