'use strict';

const cbConnection = require('./CouchbaseConnection');

const getSelect = (options) => {
    let connectionName = options ? options.connectionName : null;
    const bucketName = cbConnection.getConfig(connectionName).bucket;

    return "SELECT `" + bucketName + "`.* FROM `" + bucketName + "` " ;

};

const getComponentQuery = (field, options) =>{
    let query = getSelect(options) +
    ' WHERE systemHeader.systemType="' + SharedConstants.SYSTEM_TYPE_COMPONENT + '"' +
    ' AND ( documentId="' + field.documentId + '" OR documentId="' + field.componentName + '"' +
    ' OR name="' + field.componentName +'" )';

    return query;
};

const getComponentLibrariesQuery = (libDocs, options) =>{

    let docIds = [];
    let serviceNames = [];

    for (var i=0; i<libDocs.length; i++){
        var item = libDocs[i];
        if (item.documentId){
            docIds.push(item.documentId);
        }
        else{
            serviceNames.push(item.name);
        }
    }

    let statement =  getSelect(options) +
      ' WHERE systemHeader.systemType="' + SharedConstants.SYSTEM_TYPE_COMPONENT + '"' +
      ' AND ( documentId IN ' + JSON.stringify(docIds) + ' OR serviceName IN ' + JSON.stringify(serviceNames) + ')' ;

    return statement;
};

const getListComponentResourcesQuery = (options) =>{

    let statement =  getSelect(options) +
      ' WHERE systemHeader.systemType="' + SharedConstants.SYSTEM_TYPE_COMPONENT + '"' ;

    return statement;

};

const getVendorLibraryQuery = (name, options) =>{

    let statement = getSelect(options) +
    ' WHERE systemHeader.systemType="' + SharedConstants.SYSTEM_TYPE_VENDOR_LIBRARY + '"' +
    ' AND ( documentId=' + name + ' OR name=' + name + ')' ;

    return statement;

};

const getVendorLibrariesQuery = (options) =>{
    let statement =  getSelect(options) +
      ' WHERE systemHeader.systemType="' + SharedConstants.SYSTEM_TYPE_VENDOR_LIBRARY + '"' ;

    return statement;
};

module.exports = {

    getComponentQuery: getComponentQuery,

    getComponentLibrariesQuery: getComponentLibrariesQuery,

    getListComponentResourcesQuery: getListComponentResourcesQuery,

    getVendorLibraryQuery,

    getVendorLibrariesQuery


};
