namespace SqlDynamite.Common

open MongoDB.Driver
open MongoDB.Bson

type MongoConnection() =
    inherit NoSqlConnection()

    override this.Open () =
        let mongoUrl = MongoUrl(this._connectionString)
        let dbname = mongoUrl.DatabaseName
        let connStr = if this._connectionString.Contains("mongodb.net") && dbname <> null then this._connectionString.Replace("/" + dbname.ToString() + "?ssl=true", "?ssl=true") else this._connectionString
        let client = MongoClient(connStr)
        ignore(client.ListDatabaseNames())
        ()
        
    override this.ServerVersion with get() =
                                     let mongoUrl = MongoUrl(this._connectionString)
                                     let dbname = mongoUrl.DatabaseName
                                     let connStr = if this._connectionString.Contains("mongodb.net") && dbname <> null then this._connectionString.Replace("/" + dbname.ToString() + "?ssl=true", "?ssl=true") else this._connectionString
                                     let client = MongoClient(connStr)
                                     let database = client.GetDatabase("local")
                                     let bsonDocument = BsonDocument(dict ["buildInfo", 1 :> obj])
                                     let bsonDocumentCommand = BsonDocumentCommand<BsonDocument>(bsonDocument) 
                                     database.RunCommand<BsonDocument>(bsonDocumentCommand).Item("version").AsString
