const mineflayer = require('mineflayer');
const fs = require('fs');
const pathfinder = require('mineflayer-pathfinder').pathfinder;
const { GoalNear } = require('mineflayer-pathfinder').goals;

const config = {
  host: "minegens.id",
  port: 25565,
  version: "1.20.1"
};

// Daftar akun bot
const botAccounts = [
  //{ username: "RenTakamori", password: "Kyouka19"  },
 // { username: "SenjoHutagi", password: "RenTakamori00", command: "/is"  },
  //{ username: "GunturKzy", password: "RenTakamori00", command: "/is"  },
  { username: "KuroYamiis", password: "KuroID991", command: "/afk"  },
];

const databaseFile = 'database.json';
let userDatabase = {};

if (fs.existsSync(databaseFile)) {
  userDatabase = JSON.parse(fs.readFileSync(databaseFile, 'utf8'));
}

function createBot(account, delay) {
  setTimeout(() => {
    const bot = mineflayer.createBot({
      host: config.host,
      port: config.port,
      username: account.username,
      version: config.version,
    });

    bot.loadPlugin(pathfinder);

    bot.once('login', () => {
      console.log(`Bot ${bot.username} berhasil masuk`);
    });

    bot.once('spawn', () => {
      console.log(`Bot ${bot.username} telah spawn`);

      setTimeout(() => {
        if (!userDatabase[account.username]) {
          bot.chat(`/register ${account.password}`);
          userDatabase[account.username] = true;
          fs.writeFileSync(databaseFile, JSON.stringify(userDatabase, null, 2));
          console.log(`Mendaftarkan akun ${account.username}`);
        } else {
          bot.chat(`/login ${account.password}`);
          console.log(`Login sebagai ${account.username}`);
        }
      }, 5000);

      setTimeout(() => {
        bot.chat('/server tycoon');
        console.log(`Bot ${account.username} masuk ke realm Tycoon`);
      }, 10000);
        
      setTimeout(() => {
        bot.chat(`${account.command}`);
        console.log(`Bot ${account.username} command ${account.command}`);
      }, 17000);
    
      setTimeout(() => {
        bot.chat('/spin');
        console.log(`Bot ${account.username} Berputar`);
      }, 19000);
        
      const messages = [
          "ヽ(・∀・)ノ",
          "(^▽^)",
          "(*^‿^*)",
          "(≧◡≦)",
          "(⁀ᗢ⁀)",
          "╰(°▽°)╯",
          "(✿◕‿◕)",
          "(o^▽^o)",
          "(。♥‿♥。)",
          "(~‾▿‾)~"
        ];

      function getRandomMessage() {
        return messages[Math.floor(Math.random() * messages.length)];
      }  
//      function randomChat() {
//        bot.chat('/spin');
//      }
//      setInterval(randomChat, 420000); 
    });
    bot.on('message', (message) => {
      const text = message.toAnsi();
     	if (!text.includes("Level Progress:") && !text.includes("Next Rewards in")) {
        console.log(`Bot ${bot.username} | ${text}`);
      }
    });
      
    bot.once('kicked', (reason) => {
      console.log(`Bot ${bot.username} dikeluarkan: ${reason}`);
      reconnect(bot, account);
    });

    bot.once('error', (err) => {
      console.error(`Terjadi kesalahan pada ${bot.username}: ${err}`);
      reconnect(bot, account);
    });

    bot.once('death', () => {
      console.log(`Bot ${bot.username} mati, respawning...`);
      setTimeout(() => bot.chat('/respawn'), 5000);
    });
  }, delay);
}

function reconnect(bot, account) {
  console.log(`Bot ${account.username} mencoba untuk masuk kembali...`);
  bot.end(); // Pastikan instance lama dihentikan sebelum reconnect
  setTimeout(() => createBot(account, 5000), 5000);
}

// Jalankan semua bot dengan delay 15 detik antar akun
botAccounts.forEach((account, index) => {
  createBot(account, index * 60000);
});