/*
Copyright (c) 2011, Chris Umbel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var IndexFile = require('./index_file'),
  DataFile = require('./data_file');

function pushResults(data, results, offsets, callback) {
  var wordnet = this;

  if(offsets.length == 0) {
    callback(results);
  } else {
    data.get(offsets.pop(), function(record) {
      results.push(record);
      wordnet.pushResults(data, results, offsets, callback);
    });
  }
}

function lookupFromFiles(files, results, word, callback) {
  var wordnet = this;

  if(files.length == 0)
    callback(results);
  else {
    var file = files.pop();

    file.index.lookup(word, function(record) {
      if(record) {
        wordnet.pushResults(file.data, results, record.synsetOffset, function() {
          wordnet.lookupFromFiles(files, results, word, callback);
        });
      } else {
        wordnet.lookupFromFiles(files, results, word, callback);
      }
    });
  }
}

function lookup(word, callback) {
  word = word.toLowerCase().replace(/\s+/g, '_');

  this.lookupFromFiles([
    {index: this.nounIndex, data: this.nounData},
    {index: this.verbIndex, data: this.verbData},
    {index: this.adjIndex, data: this.adjData},
    {index: this.advIndex, data: this.advData},
  ], [], word, callback);
}

function get(synsetOffset, pos, callback) {
  var dataFile = this.getDataFile(pos);
  var wordnet = this;

  dataFile.get(synsetOffset, function(result) {
    callback(result);
  });
}

function getDataFile(pos) {
    switch(pos) {
      case 'n':
        return this.nounData;
      case 'v':
        return this.verbData;
      case 'a': case 's':
        return this.adjData;
      case 'r':
        return this.advData;
    }
}

function loadSynonyms(synonyms, results, ptrs, callback) {
  var wordnet = this;

  if(ptrs.length > 0) {
    var ptr = ptrs.pop();

    this.get(ptr.synsetOffset, ptr.pos, function(result) {
      synonyms.push(result);
      wordnet.loadSynonyms(synonyms, results, ptrs, callback);
    });
  } else {
    wordnet.loadResultSynonyms(synonyms, results, callback);
  }
}

function loadResultSynonyms(synonyms, results, callback) {
  var wordnet = this;

  if(results.length > 0) {
    var result = results.pop();
    wordnet.loadSynonyms(synonyms, results, result.ptrs, callback);
  } else
    callback(synonyms);
}

function lookupSynonyms(word, callback) {
  var wordnet = this;

  wordnet.lookup(word, function(results) {
    wordnet.loadResultSynonyms([], results, callback);
  });
}

function getSynonyms() {
  var wordnet = this;
  var callback = arguments[2] ? arguments[2] : arguments[1];
  var pos = arguments[0].pos ? arguments[0].pos : arguments[1];
  var synsetOffset = arguments[0].synsetOffset ? arguments[0].synsetOffset : arguments[0];

  this.get(synsetOffset, pos, function(result) {
    wordnet.loadSynonyms([], [], result.ptrs, callback);
  });
}

function WordNet(dataDir) {

  if (!dataDir) {
    try {
      var WNdb = require('WNdb');
    } catch(e) {
      console.error("Please 'npm install WNdb' before using WordNet module or specify a dict directory.");
      throw e;
    }
    dataDir = WNdb.path;
  }

  this.nounIndex = new IndexFile(dataDir, 'noun');
  this.verbIndex = new IndexFile(dataDir, 'verb');
  this.adjIndex = new IndexFile(dataDir, 'adj');
  this.advIndex = new IndexFile(dataDir, 'adv');

  this.nounData = new DataFile(dataDir, 'noun');
  this.verbData = new DataFile(dataDir, 'verb');
  this.adjData = new DataFile(dataDir, 'adj');
  this.advData = new DataFile(dataDir, 'adv');

  this.get = get;
  this.lookup = lookup;
  this.lookupFromFiles = lookupFromFiles;
  this.pushResults = pushResults;
  this.loadResultSynonyms = loadResultSynonyms;
  this.loadSynonyms = loadSynonyms;
  this.lookupSynonyms = lookupSynonyms;
  this.getSynonyms = getSynonyms;
  this.getDataFile = getDataFile;
}

module.exports = WordNet;
