'use strict';

var through2 = require('through2');
var promise = require('promisepipe');
var dom5 = require('dom5');
var pred = dom5.predicates;
var _ = require('lodash');
var got = require('got');

function readHTML(uri) {
  if (!uri) {
    throw new Error('URI or html string is null');
  }

  if (_.startsWith(uri, 'file://')) {
    return fs.createReadStream(uri);
  } else if (_.startsWith(uri, 'http')) {
    return got(uri);
  } else {
    var Readable = require('stream').Readable;
    var stream = new Readable();
    stream.push(uri);
    stream.push(null);
    return stream;
  }
}

function tackLink() {
  return through2(function (data, enc, done) {
    var stream = this;
    var dom = dom5.parse(data.toString('utf8'));
    var links = dom5.queryAll(dom, pred.hasTagName('link'));

    links.forEach(function (link) {
      link.attrs.forEach(function(attr) {
        if (attr.name === 'href' && attr.value.indexOf('fonts.googleapis.com') !== -1) {
          stream.push(attr.value);
        }
      });
    });
    done();
  });
}

function gotFontManifest() {
  return through2.obj(function (data, enc, done) {
    console.log(data);
    return got('http:' + data.value);
    done();
  });
}

function gotFonts() {
  return through2.obj(function (data, enc, done) {
    console.log(gotFonts, data);
    done();
    // return got(data.value);
  });
}

function imports(uri) {
  return promise(
    readHTML(uri),
    tackLink(),
    got()
    // gotFontManifest()
  );
}

module.exports = imports;

@@ -626,16 +626,20 @@
 through2
+.obj
 (functio
@@ -748,16 +748,24 @@
 links = 
+_.pluck(
 dom5.que
@@ -803,72 +803,97 @@
 k'))
-;%0A%0A    links.forEach(function (link) %7B%0A      link.attrs.forEach(
+, 'attrs%5B1%5D.value');%0A%0A    _.each(links, function (url, index) %7B%0A      got('http:' + url, 
 func
@@ -897,20 +897,24 @@
 unction(
-attr
+err, css
 ) %7B%0A    
@@ -921,134 +921,63 @@
     
-if (attr.name === 'href' && attr.value.indexOf('fonts.googleapis.com') !== -1) %7B%0A          stream.push(attr.value);%0A        %7D%0A
+stream.push(%7B%0A          url: url,%0A          css: css%0A  
     
@@ -986,187 +986,94 @@
 %7D);%0A
+%0A
     
-%7D);%0A    done();%0A  %7D);%0A%7D%0A%0Afunction gotFontManifest() %7B%0A  return through2.obj(function (data, enc, done) %7B%0A    console.log(data);%0A    return got('http:' + data.value
+    if (index === links.length - 1) %7B%0A          done();%0A        %7D%0A      %7D
 );%0A    
-done(
+%7D
 );%0A 
@@ -1173,22 +1173,28 @@
 log(
+'
 got
-Fonts
+ font'
 , data
+.url
 );%0A 
@@ -1208,39 +1208,8 @@
 ();%0A
-    // return got(data.value);%0A
   %7D)
@@ -1301,33 +1301,13 @@
  got
-()%0A    // gotFontManifest
+Fonts
 ()%0A 

Create multiple got stream