import {get as httpGet} from 'http';
import {get as httpsGet} from 'https';

// thanks https://www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/
const getContent = function(url) {
  // return new pending promise
  return new Promise((resolve, reject) => {
    // select http or https module, depending on reqested url
    const get = url.startsWith(`https`) ? httpsGet : httpGet;
    const request = get(url, response => {
      // handle http errors
      if (response.statusCode < 200 || response.statusCode > 299) {
        reject(new Error(`Failed to load page, status code: ${response.statusCode}`));
      }
      // temporary data holder
      const body = [];
      // on every content chunk, push it to the data array
      response.on(`data`, chunk => body.push(chunk));
      // we are done, resolve promise with those joined chunks
      response.on(`end`, () => resolve(body.join(``)));
    });
    // handle connection errors of the request
    request.on(`error`, err => reject(err));
  });
};

class IPFSGatewayStorage {
  constructor(apiRoot = ``) {
    this.apiRoot = apiRoot;
  }

  get(key) {
    if (!key.match(/^\/ip(fs|ns)\//)) {
      key = `/ipfs/${key}`;
    }
    return getContent(this.apiRoot + key);
  }

  remove() {
    return Promise.resolve();
  }

  put() {
    return Promise.resolve();
  }
}

export default IPFSGatewayStorage;

@@ -1,79 +1,348 @@
-import %7Bget as httpGet%7D from 'http';%0Aimport %7Bget as httpsGet%7D from 'https';
+function browserGet(url) %7B%0A  return new Promise(resolve =%3E %7B%0A    const xmlHttp = new XMLHttpRequest();%0A    xmlHttp.onreadystatechange = () =%3E %7B%0A      if (xmlHttp.readyState === 4 && xmlHttp.status === 200)%0A        resolve(xmlHttp.responseText);%0A    %7D;%0A    xmlHttp.open(%60GET%60, url, true); // true for asynchronous%0A    xmlHttp.send(null);%0A  %7D);%0A%7D
 %0A%0A//
@@ -424,35 +424,16 @@
 es/%0A
-const getContent = 
 function
 (url
@@ -428,16 +428,24 @@
 function
+ nodeGet
 (url) %7B%0A
@@ -592,19 +592,19 @@
   const 
-get
+lib
  = url.s
@@ -628,26 +628,42 @@
 ) ? 
-httpsGet : 
+require(%60https%60) : require(%60
 http
-Get
+%60)
 ;%0A  
@@ -680,16 +680,20 @@
 quest = 
+lib.
 get(url,
@@ -1291,17 +1291,209 @@
 %0A  %7D);%0A%7D
-;
+%0A%0Afunction getContent(url) %7B%0A  if (typeof require !== %60undefined%60 && require.resolve(%60http%60) && require.resolve(%60https%60)) %7B%0A    return nodeGet(url);%0A  %7D else %7B%0A    return browserGet(url);%0A  %7D%0A%7D
 %0A%0Aclass 

use XHR for browser GET