"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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 (_) 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 });
var documentConnector_1 = require("../documentConnector");
var documentConnectorBase_1 = require("../documentConnectorBase");
var prisma_datamodel_1 = require("prisma-datamodel");
var mongodb_1 = require("mongodb");
var BSON = require("bson");
var prisma_datamodel_2 = require("prisma-datamodel");
var reservedSchemas = ['admin', 'local'];
var MongoCursorIterator = /** @class */ (function () {
    function MongoCursorIterator(cursor) {
        this.cursor = cursor;
    }
    MongoCursorIterator.prototype.hasNext = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.cursor.hasNext()];
            });
        });
    };
    MongoCursorIterator.prototype.next = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.cursor.next()];
                    case 1: return [2 /*return*/, (_a.sent()) || {}];
                }
            });
        });
    };
    MongoCursorIterator.prototype.close = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.cursor.close()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return MongoCursorIterator;
}());
var MongoConnector = /** @class */ (function (_super) {
    __extends(MongoConnector, _super);
    function MongoConnector(client) {
        var _this = _super.call(this) || this;
        if (!(client instanceof mongodb_1.MongoClient)) {
            throw new Error('MongoClient instance needed for initialization.');
        }
        if (!client.isConnected()) {
            throw new Error('Please connect the mongo client first.');
        }
        _this.client = client;
        return _this;
    }
    MongoConnector.prototype.getDatabaseType = function () {
        return prisma_datamodel_1.DatabaseType.mongo;
    };
    MongoConnector.prototype.listSchemas = function () {
        return __awaiter(this, void 0, void 0, function () {
            var adminDB, databases;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        adminDB = this.client.db().admin();
                        return [4 /*yield*/, adminDB.listDatabases()];
                    case 1:
                        databases = (_a.sent()).databases;
                        return [2 /*return*/, databases
                                .map(function (x) { return x.name; })
                                .filter(function (x) { return reservedSchemas.indexOf(x) < 0; })];
                }
            });
        });
    };
    MongoConnector.prototype.getInternalCollections = function (schemaName) {
        return __awaiter(this, void 0, void 0, function () {
            var db, collections;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        db = this.client.db(schemaName);
                        return [4 /*yield*/, db.collections()];
                    case 1:
                        collections = (_a.sent());
                        return [2 /*return*/, collections.map(function (collection) {
                                return { name: collection.collectionName, collection: collection };
                            })];
                }
            });
        });
    };
    MongoConnector.prototype.getInternalCollection = function (schemaName, collectionName) {
        return __awaiter(this, void 0, void 0, function () {
            var db;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        db = this.client.db(schemaName);
                        return [4 /*yield*/, db.collection(collectionName)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    MongoConnector.prototype.sampleOne = function (collection) {
        return __awaiter(this, void 0, void 0, function () {
            var cursor;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, collection.find({}).limit(1)];
                    case 1:
                        cursor = _a.sent();
                        return [2 /*return*/, new MongoCursorIterator(cursor)];
                }
            });
        });
    };
    MongoConnector.prototype.sampleMany = function (collection, limit) {
        return __awaiter(this, void 0, void 0, function () {
            var cursor;
            return __generator(this, function (_a) {
                cursor = collection.aggregate([{ $sample: { size: limit } }]);
                return [2 /*return*/, new MongoCursorIterator(cursor)];
            });
        });
    };
    MongoConnector.prototype.sampleAll = function (collection) {
        return __awaiter(this, void 0, void 0, function () {
            var cursor;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, collection.find({})];
                    case 1:
                        cursor = _a.sent();
                        return [2 /*return*/, new MongoCursorIterator(cursor)];
                }
            });
        });
    };
    MongoConnector.prototype.exists = function (collection, id) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, collection.find({ _id: id }).hasNext()];
            });
        });
    };
    /**
     * Mongo special handling of ObjectID types.
     */
    MongoConnector.prototype.inferType = function (value) {
        var suggestion = _super.prototype.inferType.call(this, value);
        if (suggestion.type === documentConnector_1.ObjectTypeIdentifier) {
            // Special BSON types. DateTime is JS DateTime and handled by base class.
            if (value instanceof BSON.ObjectID) {
                suggestion.type = prisma_datamodel_2.TypeIdentifiers.id;
                suggestion.isRelationCandidate = true;
            }
            else if (value instanceof BSON.Binary) {
                throw new documentConnector_1.UnsupportedTypeError('Type not supported', 'Binary');
            }
            else if (value instanceof BSON.BSONRegExp || value instanceof RegExp) {
                throw new documentConnector_1.UnsupportedTypeError('Type not supported', 'RegExp');
            }
            else if (value instanceof BSON.Code) {
                throw new documentConnector_1.UnsupportedTypeError('Type not supported', 'Code');
            }
            else if (value instanceof BSON.Int32) {
                suggestion.type = prisma_datamodel_2.TypeIdentifiers.integer;
            }
            else if (value instanceof BSON.Timestamp) {
                throw new documentConnector_1.UnsupportedTypeError('Type not supported', 'Timestamp');
            }
            else if (value instanceof BSON.Long) {
                suggestion.type = prisma_datamodel_2.TypeIdentifiers.long;
            }
            else if (value instanceof BSON.Decimal128) {
                throw new documentConnector_1.UnsupportedTypeError('Type not supported', 'Decimal128');
            }
        }
        return suggestion;
    };
    return MongoConnector;
}(documentConnectorBase_1.DocumentConnector));
exports.MongoConnector = MongoConnector;
//# sourceMappingURL=mongoConnector.js.map