// sample code for creating annotation items (TODO: convert to test)

var importer = require('../util/mapJsonToItemAnnotation'), siteQueries = require('./siteQueries');
var importLimit = 5;

GLOBAL.config = require('../config.js').config;
GLOBAL.config.indexer = require('../lib/indexer.js');
GLOBAL.config.pubsub = require('../lib/pubsub.js');

var i = 0;
// get your field mappings
var fieldMappings = require(process.argv[2] || '../test/mock/fieldMapping.json');

importer.init(fieldMappings);

// get your data
var data = require(process.argv[3] || '../test/mock/mesh.json');

// process results
var imported = 0, failed = 0, count = 0, queued = { tags: 'import', relevance: 0, attempts: 0, lastAttempt: new Date().toISOString() }

// do the actual import, limited by importLimit;
data.forEach(function(d) {
  count++;
  try {
    // find uri from pubmed
    if (!d.uri) {
      siteQueries.findPubMedArticle(d.Title, function(err, res) {
        if (err || !res) {
          d.uri = 'http://www.ncbi.nlm.nih.gov/pubmed/?term=' + d.Title.replace(/ /g, '+');
        } else {
          d.uri = 'http://www.ncbi.nlm.nih.gov/pubmed/' + res;
        }
        doImport(d);
      });
    } else {
      doImport(d);
    }

  } catch (e) {
    console.log('error', e);
    failed++;
  }

  // print stats
  if (count === data.length) {
    console.log('imported', imported, 'failed', failed);
    // fields that were not mapped
    console.log('unmapped', importer.getUnMapped());
  }

  if (importLimit > 0 && count === importLimit) {
    console.log('reached import limit');
    return;
  }
});


function doImport(d) {
  var r = importer.mapToItem(d, { queued: queued });

  console.log('ITEM', r.contentItem._id, r.annotations.length);
  var cItem = r.contentItem, annotations = r.annotations;
  cItem.queued = queued;
  cItem.visitors = [{ member: 'import', '@timestamp': new Date().toISOString() }];
  cItem.annotations = annotations;
  GLOBAL.config.indexer._saveContentItem(cItem);
  // FIXME only works for items with abstract content
  GLOBAL.config.pubsub.requestAnnotate(cItem.uri, cItem.content);

  imported++;
}

// utility assigns field value
function fv(vals, key) {
  if (!vals) return;
  vals.forEach(function(v) {
    if (v.key === key && vals[key] !== 'Not available') {
      return vals[key];
    }
  });
}

// add any function value assigners
importer.funcVal('uri', function(data) { 
  var uri = data.uri || fv(data.vals.LinkFullPaper) || fv(data.vals.linkPubMed) || fv(data.vals.linkJrn);
  if (!uri) {
    throw Error('No uri');
  }
  return uri;
});


@@ -182,16 +182,110 @@
 mit = 5;
+%0Avar LOOKUP_URIS = false, SAVE = true;%0A%0Aconsole.log('LOOKUP_URIS', LOOKUP_URIS, 'SAVE', SAVE);
 %0A%0AGLOBAL
@@ -960,16 +960,31 @@
  (!d.uri
+ && LOOKUP_URIS
 ) %7B%0A    
@@ -1294,24 +1294,109 @@
    %7D else %7B%0A
+      if (!d.uri && !LOOKUP_URIS) %7B%0A        d.uri = 'http://NOURI/' + count;%0A      %7D%0A
       doImpo
@@ -2126,16 +2126,32 @@
 ations;%0A
+  if (SAVE) %7B%0A  
   GLOBAL
@@ -2191,16 +2191,18 @@
 cItem);%0A
+  
   // FIX
@@ -2247,16 +2247,18 @@
 content%0A
+  
   GLOBAL
@@ -2314,16 +2314,20 @@
 ontent);
+%0A  %7D
 %0A%0A  impo

add debugging