const CommandContext = require('./command-context');
const ParsedCommand = require('./parsed-command');

class CommandReader {
  constructor () {
    this._commands = {};
  }

  get commands () {
    return this._commands;
  }

  addCommand(command) {
    console.log("adding command", command.name);
    this.commands[command.name] = command;
  }

  msgIsCommand(message) {
    if (message.content.indexOf('!') !== 0) {
      return false;
    }

    let commandName = message.content.split(' ')[0].slice(1);
    return typeof this.commands[commandName] !== 'undefined';
  }

  parse(message, nix) {
    let commandParts = message.content.split(' ');
    let commandName = commandParts[0].slice(1); //slice to strip the command prefix
    let command = this.commands[commandName];

    let inputArray = commandParts.slice(1); //Discard the name portion of the message
    let argsObject = {};
    let flagsObject = {};

    command.args.forEach((arg, index) => {
      let value = inputArray.shift();

      if (index === command.args.length - 1 && inputArray.length >= 1) {
        value += ' ' + inputArray.join(' ');
      }

      if (typeof value === "undefined") {
        argsObject[arg.name] = arg.default;
      } else {
        argsObject[arg.name] = value;
      }
    });

    let context = new CommandContext(message, argsObject, flagsObject, nix);
    return new ParsedCommand(command, context);
  }
}

module.exports = CommandReader;

@@ -98,16 +98,39 @@
 and');%0A%0A
+COMMAND_PREFIX = '!';%0A%0A
 class Co
@@ -399,16 +399,17 @@
     if (
+!
 message.
@@ -420,26 +420,34 @@
 ent.
-indexOf('!') !== 0
+startsWith(COMMAND_PREFIX)
 ) %7B%0A
@@ -645,44 +645,45 @@
 mand
-Parts = message.content.split(' '
+Data = this._parseMessage(message
 );%0A
+%0A
     
@@ -693,20 +693,16 @@
  command
-Name
  = comma
@@ -707,109 +707,21 @@
 mand
-Parts%5B0%5D.slice(1); //slice to strip the command prefix%0A    let command = this.commands%5BcommandName%5D;%0A
+Data.command;
 %0A   
@@ -730,21 +730,17 @@
 et input
-Array
+s
  = comma
@@ -745,65 +745,21 @@
 mand
-Parts.slice(1); //Discard the name portion of the message
+Data.inputs;%0A
 %0A   
@@ -1300,16 +1300,530 @@
 xt);%0A  %7D
+%0A%0A  _parseMessage(message) %7B%0A    let msgParts = message.content.split(/ (.+)/); //split into name and input parts%0A%0A    let name = msgParts%5B0%5D.slice(COMMAND_PREFIX.length); //slice to strip the command prefix%0A    let command = this.commands%5Bname%5D;%0A%0A    let inputs = %5B%5D;%0A%0A    if (typeof msgParts%5B1%5D !== %22undefined%22) %7B%0A      let values = msgParts%5B1%5D.match(/%5C%7B.*%5C%7D%7C%22%5B%5E%22%5D*%22%7C'%5B%5E'%5D*'%7C%5CS+/g);%0A      if (values) %7B%0A        inputs = values;%0A      %7D%0A    %7D%0A%0A    return %7B%0A      command: command,%0A      inputs: inputs,%0A    %7D;%0A  %7D
 %0A%7D%0A%0Amodu

move message parsing to fuction