var irc = require('irc');
var sp = require('wordsworth').getInstance();
var client = new irc.Client('chat.freenode.net', 'zzzz-spellbot', { channels: ['#citrt']});
var fs = require('fs');

function init(){
  client.say('#citrt','Loading dictionary');
  sp = require('wordsworth').getInstance();
  sp.initialize('seed.txt', 'training.txt', function(){
    client.say('#citrt','Dictionary loaded.');
  });
}

init();

function learn(word){
  fs.appendFile('seed.txt', word + "\r\n");
  init();
}

client.addListener('message', function(from, to, message){
  var cmd = message.match(/^learn (.*)/)

  if (cmd) {
    learn(cmd[1]);
  } else {
    var errors = sp.analyze(message);
    console.log("Message from " + from);
    Object.keys(errors).forEach(function(wrong){
      var right = errors[wrong];
      if (typeof(right[0]) == 'undefined'){
        client.say('#citrt', from + ": I don't know the word " + wrong);
      } else {
        client.say('#citrt', from + ": I think what you meant by " + wrong + " was " + right[0]);
      }
    });
  }
});

client.addListener('error', function(message) {
    console.log('error: ', message);
});