const { EmbedBuilder, AttachmentBuilder } = require('discord.js');
const unirest = require('unirest');
const download = require('download-file');
const notDefined = require("is-not-defined");

function createDictionaryEmbed(word, phonetic, meaningsArray, user) {
  return new EmbedBuilder()
    .setColor("#FF0000")
    .setTitle(word + ": " + phonetic)
    .addFields(meaningsArray)
    .setTimestamp()
    .setFooter({
      text: `Requested by ${user.tag}`,
      iconURL: `${user.displayAvatarURL()}`
    });
}

module.exports = {
  name: "dictionary",
  description: "Returns information about a word",
  options: [{
    name: "word",
    description: "The data you would like inside of the QR",
    required: true,
    type: 3 // 6 is type USER
  }],
  async run(client, interaction) {
    let rand = Math.floor(Math.random() * 99999).toString();
    let word = interaction.options._hoistedOptions[0].value;
    let meaningsArray = [];

    let response = await unirest
      .get(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`)
      .headers({
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      });

    let data = response.body[0];
    if (notDefined(data)) {
      return interaction.editReply("Sorry, nothing was found!");
    }

    let phonetic = data.phonetics[1] ? data.phonetics[1].text : "";
    let audio = data.phonetics[0].audio;
    if (!audio) {
      for (let wordData of data.meanings) {
        let definition = wordData.definitions[0];
        meaningsArray.push({
          name: wordData.partOfSpeech,
          value: `${definition.definition}\nExample: ${definition.example || ""}`
        });
      }
      let embed = createDictionaryEmbed(word, phonetic, meaningsArray, interaction.user);
      interaction.editReply({ embeds: [embed] });
      meaningsArray = [];
      rand = Math.floor(Math.random() * 99999).toString();
    } else {
      // Options for Audio Download
      let options = {
        directory: "./audio/",
        filename: rand + ".mp3"
      }
    
      download(audio, options, function(err) {
        if (err) throw err;
        for (let wordData of data.meanings) {
          let definition = wordData.definitions[0];
          meaningsArray.push({
            name: wordData.partOfSpeech,
            value: `${definition.definition}\nExample: ${definition.example || ""}`
          });
        }
        let file = new AttachmentBuilder(`./audio/${rand}.mp3`);
        let embed = createDictionaryEmbed(word, phonetic, meaningsArray, interaction.user);
        interaction.editReply({ files: [file], embeds: [embed] });
        meaningsArray = [];
        rand = Math.floor(Math.random() * 99999).toString();
      });
    }
  }    
}