// Create a new db and fill it with the CISP info
// TODO: remove this step and create a persistent DB object
// Using lokiJS, because it is enough and fast
var db = new loki('db.json');

// CISP database collection
var cisp = db.addCollection('cisp2db');
cisp.ensureUniqueIndex("Description");
cisp.ensureUniqueIndex("Code");

// Legal words database collection
var words = db.addCollection('vocabulaire2db');
words.ensureUniqueIndex("Word");

function extractWords (a) {
  console.log("Done extracting words");
  // Array of obj -> Array of arrays
  var r = a.map(function (o) {
    return  [ o.Code, o.Description ];
  });

  // Array of arrays -> Array of words
  r = r.reduce(function (pv,cv,i,a) {
    return cv.concat(pv);
  },[]);

  // Array of words -> Array of objs { 'Words': … }
  return r.map(function (w) {
    return { 'Word': w };
  });
}

// Download CSV file in the background
$.ajax({
    url: "./cisp2fr.csv",
    async: true,
    success: function (csvd) {
      var o = $.csv.toObjects(csvd);
      cisp.insert(o);
      words.insert(extractWords(o));
    },
    dataType: "text",
    complete: function () {
      main();
    }
});

function displayMany (a) {
  var out = a.map(function (o) {
    var d = cisp.by("Description", o.Word);
    var ds = d ?
            "<tr><td>"+d.Code+"</td>"
          + "<td>"+d.Description+"</td>"
          + "<td>"+d.Thème+"</td>"
          + "<td>"+d.Catégorie+"</td></tr>"
        : "";
    var cs = "";
    if (ds != "") {
      var c = cisp.by("Code", o.Word);
      cs = c ?
          "<tr><td>"+c.Code+"</td>"
          + "<td>"+c.Description+"</td>"
          + "<td>"+c.Thème+"</td>"
          + "<td>"+c.Catégorie+"</td></tr>"
        : "";
    }
    return ds + cs;
  }).reduce(function (pv,cv,i,a) {
    return pv + cv;
  },"");

  var table = "<table>";
  table += "<tr>";
  table += "<th>Code</th>";
  table += "<th>Description</th>";
  table += "<th>Thème</th>";
  table += "<th>Catégorie</th>";
  table += "</tr>";

  table += out;

  table += "</table>";
  return table;
}

// Main application
function main() {
  console.log(cisp.data);
  console.log(words.data);
  $( "#question" ).keyup(function () {
    var str = $( "#question" ).val();
    var ans = words.find({'Word': { '$contains': str}});
    console.log("Words found: ",ans);
    console.log(displayMany(ans));
    $( "#answer" ).empty().append(displayMany(ans));
  });
}