const mineflayer = require('mineflayer')
const { pathfinder, Movements, goals: { GoalNear } } = require('mineflayer-pathfinder')
const fs = require('fs');

global.bot = null
global.defaultMove = null

module.exports = {
    get: function () {
        return global.bot
    },
    create: function () {
        const data = fs.readFileSync('.env').toString();
        const sp = data.split('\n')
        global.bot = mineflayer.createBot({
            host: 'sc.on.underlying.skynet.tpgc.me',
            port: 25565,
            auth: 'microsoft',
            username: sp[0],
            password: sp[1]
        })
        global.bot.loadPlugin(pathfinder)
        return global.bot
    },
    spawn: function () {
        global.defaultMove = new Movements(bot)
    },
    printWelcomeChat: function () {
        bot.chat('<gradient:#199be6:#46d61a:#ebac1a>Cum Bot v0.1')
        bot.chat('<#46d61a>For a list of commands do !help')
        bot.chat('<#9d9e9e>-----------------------------------')
    },
    printHelpmessage: function () {
        bot.chat("<#9d9e9e>-----------------------------------")
        bot.chat("<#46d61a>!spawn   - Prints out the world spawn")
        bot.chat("<#46d61a>!goto    - Send the bot to a position")
        bot.chat("<#46d61a>!follow  - Follow you")
        bot.chat("<#46d61a>!come    - Goto your current position")
        bot.chat("<#9d9e9e>-----------------------------------")
    },
    come: function (username) {
        const target = global.bot.players[username]?.entity
        if (!target) {
            bot.chat("I am unable to see you!")
            return
        }
        const { x: playerX, y: playerY, z: playerZ } = target.position

        const RANGE_GOAL = 1 // get within this radius of the player
        global.bot.pathfinder.setMovements(defaultMove)
        global.bot.pathfinder.setGoal(new GoalNear(playerX, playerY, playerZ, RANGE_GOAL))
    }
}