const bot_util = require('./bot')
const bot = bot_util.create()
const items = require('./items')
const { Vec3 } = require('vec3')
const insult = require('./insult')

function processQueue(){

}

bot.once('login', () => {
  //bot_util.printWelcomeChat()
  // bot.chatAddPattern(
  //   /(!([a-z|A-Z])+)/,
  //   'command',
  //   'Someone issues a command'
  // )
})
bot.on('spawn', () => {
  bot_util.spawn()
  setInterval(processQueue, 50)
  //bot.chat('I spawned, watch out!')
})

function handleCommand(command, message, func) {
  const result = new RegExp(command).exec(message);
  if (result) {
    func(result)
  }
}

function sayBlockUnder() {
  const block = bot.blockAt(bot.players[username].entity.position.offset(0, -1, 0))
  bot.chat(`Block under you is ${block.displayName} in the ${block.biome.name} biome`)
  console.log(block)
}

function levels(exp){
  if (exp > 1508)
    return (325.0 / 18.0) + Math.sqrt((2.0 / 9.0) * (exp - (54215.0 / 72.0)))
  else if (exp > 353)
    return (81.0 / 10.0) + Math.sqrt((2.0 / 5.0) * (exp - (9839.0 / 40.0)))
  else
    return Math.sqrt(exp + 9) - 3
}

function printStats() {
  bot.chat("Here are my current stats")
  bot.chat("Experience Level(s): " + levels(bot.experience.level))
  bot.chat("Health: " + bot.health)
  bot.chat("Food: " + bot.food)
}

function handleMessage(username, message) {
  if (username === bot.username)
    return
  handleCommand("!help", message, (result) => bot_util.printHelpmessage())
  handleCommand("!spawn", message, (result) => bot.chat(`Spawn is at ${bot.spawnPoint}`))
  handleCommand("!stats", message, (result) => printStats())
  handleCommand("!come", message, (result) => bot_util.come(username))
}

bot.on('chat', (username, message) => {
  handleMessage(username, message)
})

bot.on('message', (message) => {
  console.log(message.toAnsi())
})

bot.on('whisper', (username, message, rawMessage) => {
  handleMessage(username, message);
})

bot.on('entityDead', (entity) => insult.insult(bot, entity))

// Log errors and kick reasons:
bot.on('kicked', console.log)
bot.on('error', console.log)