import { REST, Routes, Client, Events, GatewayIntentBits } from 'discord.js';
import { spawn } from "node:child_process";
import { mkdir, cp } from 'node:fs/promises';

let sessions = {};
let channels = {};

const { TOKEN, ID } = process.env;
//const commands = [];
//const rest = new REST({ version: '10' }).setToken(TOKEN);

try {
  console.log('Started refreshing application (/) commands.');

  //await rest.put(Routes.applicationCommands(ID), { body: commands });

  console.log('Successfully reloaded application (/) commands.');
} catch (error) {
  console.error(error);
}

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessages] });

client.on(Events.ClientReady, readyClient => {
  console.log(`Logged in as ${readyClient.user.tag}!`);
});

client.on(Events.MessageCreate, async interaction => {
  if (interaction.author.bot) return;
  let msg = interaction.content;
  let channel = interaction.channel.name;

  if (channel.indexOf('play') == -1 && channel.indexOf('bot') == -1 && channel.indexOf('spam') == -1) return;

  if (msg.startsWith('!')) {
    msg = `/${msg.slice(1)}`;
  }

  let id = interaction.author.id;

  if (!sessions[id]) {
    try {
      await mkdir(`./bin/${id}`);
    } catch (err) {

    }
    sessions[id] = spawn('../elem', [id], {
      'cwd': `./bin/${id}`
    });

    sessions[id].stdout.on('data', (chunk) => {
      if (chunk.toString().length > 1) {
        let str = chunk.toString();
        str = str.replaceAll(id, `<@${id}>`);
        (channels[id] || interaction.channel).send(str);
      }
    });
    sessions[id].on('close', () => {
      delete sessions[id];
    })
  }

  channels[id] = interaction.channel;

  let msgs = msg.split('\n');

  setTimeout(async function () {
    sessions[id].stdin.write(msgs[0] + '\n');
  }, 100);
});

client.login(TOKEN);