import * as Models from '../../lib/models/models';
import Mongoose = require( 'mongoose' );

export default class MoongosseConnection {
  public config: Models.UserProperties;
  public url: string;

  /** */
  public constructor( config: Models.UserProperties ) {
    this.config = config;
    this.url = `mongodb://${config?.mongoDb?.dbHost as string}:${config?.mongoDb?.dbPort as number}/${config?.mongoDb?.dbName as string}`;
    return this;
  }

  public getActiveConnections(): Mongoose.Connection[] {
    const connections = Mongoose.connections.map( ( connnection ) => connnection );
    return connections.filter( ( connection ) => connection.readyState === 1 );
  }

  public async connect(): Promise<Mongoose.Connection> {
    if ( ( this.getActiveConnections() ).length > 0 ) {
      return Mongoose.connection;
    }

    await Mongoose.connect( this.url, {
      useCreateIndex: true,
      useFindAndModify: true,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    } ).catch( ( error: Error ) => {
      console.log( error.message );
      throw error;
    } );

    const connection = Mongoose.connection;

    connection.once( 'open', () => {
      console.log( 'Connected to database' );
    } );

    connection.on( 'error', ( error: Error ) => {
      console.log( `Error connecting to database ${error.message}` );
    } );

    return connection;
  }

  /**
   * Get database size
   *
   * @returns {Promise<number>}
   * @memberof MongoDbConnection
   */
  public async getDatabaseSize( ): Promise<number> {
    const connection = await this.connect();
    const result: Models.Stats = ( await connection.db.stats( { scale: 1024 * 1024 } ) ) as Models.Stats;
    return result.dataSize;
  }
}
