const _ = require('underscore');

const IpfsModule = require('../ipfs');
const SwarmModule = require('../swarm');

class Storage {
  constructor(embark, options){
    this.embark = embark;
    this.storageConfig = embark.config.storageConfig;

    if (!this.storageConfig.enabled) return;

    this.addSetProviders();

    new IpfsModule(embark, options); /*eslint no-new: "off"*/
    new SwarmModule(embark, options); /*eslint no-new: "off"*/

    embark.events.setCommandHandler('storage:upload', (cb) => {
      let platform = options.storageConfig.upload.provider;

      if (['swarm', 'ipfs'].indexOf(platform) === -1) {
        return cb({message: __('platform "{{platform}}" is specified as the upload provider, however no plugins have registered an upload command for "{{platform}}".', {platform: platform})});
      }

      embark.events.request("storage:upload:" + platform, cb);
    });
  }

  /**
   * Adds the code to call setProviders in embarkjs after embark is ready
   * 
   * @returns {void}
   */
  addSetProviders() {
    const self = this;
    // filter list of dapp connections based on available_providers set in config
    let hasSwarm = _.contains(this.storageConfig.available_providers, 'swarm'); // don't need to eval this in every loop iteration
    // contains valid dapp storage providers
    this._validDappProviders = _.filter(this.storageConfig.dappConnection, (conn) => {
      return _.contains(self.storageConfig.available_providers, conn.provider) || (conn === '$BZZ' && hasSwarm);
    });

    let code = `\nEmbarkJS.Storage.setProviders(${JSON.stringify(this._validDappProviders)});`;
    let shouldInit = (storageConfig) => {
      return (this._validDappProviders !== undefined && this._validDappProviders.length > 0 && storageConfig.enabled === true);
    };

    this.embark.addProviderInit('storage', code, shouldInit);
  }

}

module.exports = Storage;

@@ -903,628 +903,49 @@
 %0A%0A  
-/**%0A   * Adds the code to call setProviders in embarkjs after embark is ready%0A   * %0A   * @returns %7Bvoid%7D%0A   */%0A  addSetProviders() %7B%0A    const self = this;%0A    // filter list of dapp connections based on available_providers set in config%0A    let hasSwarm = _.contains(this.storageConfig.available_providers, 'swarm'); // don't need to eval this in every loop iteration%0A    // contains valid dapp storage providers%0A    this._validDappProviders = _.filter(this.storageConfig.dappConnection, (conn) =%3E %7B%0A      return _.contains(self.storageConfig.available_providers, conn.provider) %7C%7C (conn === '$BZZ' && hasSwarm);%0A    %7D)
+addSetProviders() %7B%0A    const self = this
 ;%0A%0A 
@@ -1017,34 +1017,44 @@
 his.
-_validDappProviders
+storageConfig.dappConnection
 )%7D);%60;%0A
+%0A
     
@@ -1107,90 +1107,8 @@
 turn
- (this._validDappProviders !== undefined && this._validDappProviders.length %3E 0 &&
  sto
@@ -1129,18 +1129,8 @@
 bled
- === true)
 ;%0A  

simplify add set providers; validation can be done on the client isde