import { Injectable, Logger } from '@nestjs/common';
import nano from 'nano';
import * as DashboardModel from '../models/dashboard';
import { CouchDb } from './couchdb';
import configuration from '../configs/main-config';

const config = configuration();

@Injectable()
export class Dashboards {
  private static logger = new Logger(Dashboards.name);
  private static dashboardsDb = null;
  private static initialized = false;

  static async getDatasource(): Promise<
    nano.DocumentScope<DashboardModel.Dashboard>
  > {
    if (Dashboards.initialized) {
      return Dashboards.dashboardsDb;
    }
    Dashboards.initialized = true;
    const n = CouchDb.getCouchDb();
    const dashboardsDbName = config.couchDb?.dbs?.dashboards;
    const dbs = await n.db.list();
    if (!dbs.includes(dashboardsDbName)) {
      await n.db.create(dashboardsDbName);
    }
    Dashboards.dashboardsDb = await n.db.use(dashboardsDbName);
    Dashboards.logger.log(`Connected to dashboards db - ${dashboardsDbName}`);
    return Dashboards.dashboardsDb;
  }

  async getDatasource(): Promise<nano.DocumentScope<DashboardModel.Dashboard>> {
    return await Dashboards.getDatasource();
  }
}
