const name = 'function'
const description = 'Runs mcfunctions.'
const usages = ['run <filepath...>', 'list']
const aliases = ['function', 'func']
const enabled = true

const permLevel = 0

const fs = require('fs')

function execute (bot, cmd, player, args, handler) {
  const subCmd = args.shift()

  let filepath, files, msg
  switch (subCmd) {
    case 'run':
      filepath = `./functions/${args.join(' ').replace(/ยง./g, '')}`
      if (!filepath.endsWith('.mcfunction')) filepath += '.mcfunction'
      if (/\.\.\//.test(filepath) || !fs.existsSync(filepath)) throw new Error('Invalid function name')
      bot.runFunction(filepath)
      break
    case 'list':
      files = fs.readdirSync('./functions')
      // files.filter((file) => file.endsWith('.mid'))

      msg = [{ text: 'Functions:\n', color: bot.colors.primary }]
      files.forEach((file) => {
        msg.push(file)
        msg.push({ text: ', ', color: bot.colors.secondary })
      })
      msg.splice(-1, 1) // msg[msg.length - 1].text = '.'
      bot.core.run(`/tellraw @a ${JSON.stringify(msg)}`)
      break
    default:
      throw new Error('Missing or invalid argument')
  }
}

module.exports = { name, description, usages, aliases, enabled, execute, permLevel }