'use strict';
var log4js = require('log4js');
var logger = log4js.getLogger('Helper');
logger.setLevel('DEBUG');

var path = require('path');
var util = require('util');

var hfc = require('fabric-client');
hfc.setLogger(logger);

// couchDB config 
const CDBKVS = require("fabric-client/lib/impl/CouchDBKeyValueStore.js");

async function getClientForOrg(userorg, username) {
    logger.debug('getClientForOrg - ****** START %s %s', userorg, username)
    // get a fabric client loaded with a connection profile for this org
    let config = '-connection-profile-path';

    // build a client context and load it with a connection profile
    // lets only load the network settings and save the client for later
    let client = hfc.loadFromConfig(hfc.getConfigSetting('network' + config));

    // This will load a connection profile over the top of the current one one
    // since the first one did not have a client section and the following one does
    // nothing will actually be replaced.
    // This will also set an admin identity because the organization defined in the
    // client section has one defined
    client.loadFromConfig(hfc.getConfigSetting(userorg + config));
    
    //********************** CouchDB configuration **************************************
    // set the state store
    let stateStore = await new CDBKVS({
        url: "https://<USERNAME>:<PASSWORD>@<URL>",
        name: "<DB_NAME>"
    });

    client.setStateStore(stateStore);

    // set the cryto store
    const cryptoSuite = hfc.newCryptoSuite();

    let cryptoKS = hfc.newCryptoKeyStore(CDBKVS, {
        url: "https://<USERNAME>:<PASSWORD>@<URL>",
        name: "<DB_NAME>"
    });

    cryptoSuite.setCryptoKeyStore(cryptoKS);

    client.setCryptoSuite(cryptoSuite);
    
    //********************** CouchDB configuration END **************************************
    
    if (username) {
        let user = await client.getUserContext(username, true);
        if (!user) {
            throw new Error(util.format('User was not found :', username));
        } else {
            logger.debug('User %s was found to be registered and enrolled', username);
        }
    }
    logger.debug('getClientForOrg - ****** END %s %s \n\n', userorg, username)

    return client;
}