'use strict';

/**
 * Lint readme.md for missing reflinks, and add them to
 * package.json if enabled by the user.
 */

module.exports = function(app) {
  var re = /(\[[\w._-]+?\]\[\])/g;

  var reflinks = app.pkg.get('verb.reflinks') || [];
  var added = false;
  var count = 0;

  return function(file, next) {
    var matches = file.content.match(re);

    if (matches && matches.length) {
      matches.forEach(function(match) {
        var idx = match.indexOf(']');
        var name = match.slice(1, idx).trim();
        if (!has(reflinks, name)) {
          reflinks.push(name);
          count++;
        }
      });
    }

    if (count > 0 && !added) {
      added = true;
      var obj = {config: {reflinks: reflinks}};
      app.base.cli.process(obj, next);
    } else {
      next();
    }
  };
};

function has(keys, key) {
  return keys.indexOf(key.trim()) !== -1;
}

@@ -348,17 +348,16 @@
 ch(re);%0A
-%0A
     if (
@@ -525,13 +525,8 @@
  if 
-(!has
 (ref
@@ -534,15 +534,29 @@
 inks
-, name)
+.indexOf(name) === -1
 ) %7B%0A
@@ -693,26 +693,99 @@
     
-var obj = %7Bconfig:
+app.pkg.set('verb.reflinks', reflinks);%0A      app.pkg.logInfo('updated package.json with:',
  %7Bre
@@ -801,17 +801,17 @@
 eflinks%7D
-%7D
+)
 ;%0A      
@@ -818,34 +818,31 @@
 app.
-base.cli.process(obj,
+pkg.save();%0A     
  next
+(
 );%0A 
@@ -885,75 +885,4 @@
 %0A%7D;%0A
-%0Afunction has(keys, key) %7B%0A  return keys.indexOf(key.trim()) !== -1;%0A%7D%0A

save results directly in package.json