const { Client } = require('discord.js');
const fs = require("fs");

const client = new Client();
require('dotenv').config();

const prefix = process.env.PREFIX || 'more';
const modulFolder = "./modules/";
const komand_handlery = [];
const eventy = { on_message: [] };

const runEvent = (name, args) => {
  eventy[name].forEach(listener => {
    listener(...args);
  });
}

fs.readdirSync(modulFolder).forEach(function (soubor) {
  if (soubor.endsWith(".js")) {
    const modul = require(`${modulFolder}${soubor}`);
    Object.keys(modul).forEach(name => {
      if (name.startsWith('on_')) {
        if (!eventy[name]) {
          eventy[name] = [];
          if (name !== 'on_message') client.on(name.substring(3), (...args) => runEvent(name, args));
        }
        eventy[name].push(modul[name]);
      } else if (name === 'more_komand') komand_handlery.push(modul[name]);
    });
  }
});

client.on("message", function (mes) {
  if (process.env.IGNORE_MESS) return;

  runEvent('on_message', [mes]);
  const [mes_prefix, komand, ...args] = mes.content.split(' ');
  if (mes_prefix.toLowerCase() !== prefix) return;

  const celArgs = args.join(' ');
  for (let i = 0; i < komand_handlery.length; i++) {
    if (komand_handlery[i](mes, komand.toLowerCase(), celArgs)) return;
  }
  mes.channel.send('co to znamena ti gadzovko');
});

client.login(process.env.TOKEN);
