'use strict';

const cbConnection        = require('./../../../database/providers/couchbase/CouchbaseConnection');
const cbUtil              = require('./../../../database/providers/couchbase/CouchbaseUtil');
const healthCheckConstants     = require('../../../../shared/constants/HealthCheckConstants');

exports.check =  (options) => {
  return new Promise(async (resolve, reject) => {
    const dsName = options.connectionName;
    try {
      let cbBucket = await getBucket(dsName);
      const query = cbUtil.getN1QlQuery("SELECT 'Ok' AS ping");
      cbBucket.query(query, (err, results)  => {
        if (err) {
          reject(err);
        } else {
          resolve(healthCheckConstants.OK);
        }
      });
    } catch (error) {
      reject(error);
    }

  });
};



function getBucket(dsName){
  return new Promise(function(resolve, reject){

    let cbBucket;
    try{
      cbBucket = cbConnection.getBucket(dsName);
    }catch(err){

    }

    if (!cbBucket){
      cbConnection.initialise(dsName).then(function (connection) {
        cbBucket = cbConnection.getBucket(dsName);
        resolve(cbBucket);
      },function errorFunc(err) {
        reject(err);
      });
    }
    else{
      resolve(cbBucket);
    }
  });
}
