import logger from "../log.mjs";
import { getLevel } from "../../inc/admin.mjs";

const parseArgs = msg => {
  let args = msg.trim().split(" ")
    , cmd = args.shift();
  return {
    cmd: cmd.replace(/^(\.|\/|\!)/, ""),
    args: args
  };
};

export default async bot => {

  return [{
    name: "message",
    listener: "message",
    f: e => {
      logger.info(`${e.network} -> ${e.channel} -> ${e.user.nick}: ${e.message}`);

      let trigger;

      if(e.media) {
        trigger = [...bot._trigger.entries()].filter(t => t[1].name === "parser");
        if(!e.message)
          e.message = "";
      } else {
        trigger = [...bot._trigger.entries()].filter(t =>
          t[1].call.exec(e.message) &&
          t[1].clients.includes(e.type) &&
          t[1].active &&
          t[1].level <= getLevel(e.user).level
        );
      }

      trigger.forEach(async t => {
        try {
          await t[1].f({ ...e, ...parseArgs(e.message) });
          console.log(`triggered > ${t[0]}`);
        }
        catch(err) {
          console.error(err);
          await e.reply(`${t[0]}: An error occured.`);
          logger.error(`${e.network} -> ${e.channel} -> ${e.user.nick}: ${err.toString ? err : JSON.stringify(err)}`);
        }
      });
    }
  }];

};
