const ytdl = require("ytdl-core-discord");
const { canModifyQueue, STAY_TIME } = require("../util/LanBot");
const { MessageEmbed, MessageAttachment } = require("discord.js");
const musicGif = new MessageAttachment('./assets/img/Music.gif');
const dancingGif = new MessageAttachment('./assets/img/dancing.gif');

module.exports = {
  async play(song, message) {
    


    let config;

    try {
      config = require("../config");
    } catch (error) {
      config = null;
    }



    const PRUNING = config ? config.PRUNING : process.env.PRUNING;

    const queue = message.client.queue.get(message.guild.id);

    if (!song) {
      setTimeout(function () {
        if (queue.connection.dispatcher && message.guild.me.voice.channel) return;
        queue.channel.leave();
        queue.textChannel.send("Fin de la liste de lecture ! Je vous abandonne !");
      }, STAY_TIME * 1000);
      queue.textChannel.send("❌ La file d'attente est terminée.").catch(console.error);
      return message.client.queue.delete(message.guild.id);
    }

    let stream = null;
    let streamType = song.url.includes("youtube.com") ? "opus" : "ogg/opus";


    try {
      if (song.url.includes("youtube.com")) {stream = await ytdl(song.url, { 
          filter: format => ['251'],
          highWaterMark: 1 << 25
      }), {
          type: 'opus'
      };
    }

    } catch (error) {
      if (queue) {
        queue.songs.shift();
        module.exports.play(queue.songs[0], message);
      }

      console.error(error);
      return message.channel.send(
        "Erreur: {error}", { error: error.message ? error.message : error }
      );
    }
    queue.connection.on("disconnect", () => message.client.queue.delete(message.guild.id));

    const dispatcher = queue.connection
      .play(stream, { type: streamType })
      .on("finish", () => {
        if (collector && !collector.ended) collector.stop();

        if (queue.loop) {
          // if loop is on, push the song back at the end of the queue
          // so it can repeat endlessly
          let lastSong = queue.songs.shift();
          queue.songs.push(lastSong);
          module.exports.play(queue.songs[0], message);
        } else {
          // Recursively play the next song
          queue.songs.shift();
          module.exports.play(queue.songs[0], message);
        }
      })
      .on("error", (err) => {
        console.error(err);
        queue.songs.shift();
        module.exports.play(queue.songs[0], message);
      });
    dispatcher.setVolumeLogarithmic(queue.volume / 100);

    var date = new Date(0);
    date.setSeconds(song.duration); // specify value for SECONDS here
    var timeString = date.toISOString().substr(11, 8);

        try {
          //let DJYT = require ("discordjs-ytdl");
          let noiceEmbed = new MessageEmbed()
            .setTitle('Début de la lecture')
            .attachFiles(dancingGif)
            .setThumbnail('attachment://dancing.gif')
            .addField('Nom', song.title, true)
            .addField('Demandé par', message.author, true)
            .addField('Nombre de vues', song.views, true)
            .addField('Durée', timeString, true)
            .setImage(song.thumbnail)
            //.setImage("https://media.discordapp.net/attachments/789196713540976670/812047848047771658/lanziumbanniere.gif");
            var playingMessage = await queue.textChannel.send(noiceEmbed);
      
        //console.log(DJYT.thumbnail);
        //`🎶 A commencé à jouer: **${song.title}** ${song.url}`

      await playingMessage.react("⏭");
      await playingMessage.react("⏯");
      await playingMessage.react("🔇");
      await playingMessage.react("🔉");
      await playingMessage.react("🔊");
      await playingMessage.react("🔁");
      await playingMessage.react("🔀");
      await playingMessage.react("⏹");
    } catch (error) {
      console.error(error);
    }

    const filter = (reaction, user) => user.id !== message.client.user.id;
    var collector = playingMessage.createReactionCollector(filter, {
      time: song.duration > 0 ? song.duration * 1000 : 600000
    });

    collector.on("collect", (reaction, user) => {
      if (!queue) return;
      const member = message.guild.member(user);

      switch (reaction.emoji.name) {
        case "⏭":
          queue.playing = true;
          reaction.users.remove(user).catch(console.error);
          if (!canModifyQueue(member)) return message.channel.send("Vous devez d'abord rejoindre un salon vocal !");
          queue.connection.dispatcher.end();
          queue.textChannel.send(`${user} ⏩ a skip la musique.`).catch(console.error).then(msg => {
            msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
        });
          collector.stop();
          break;

        case "⏯":
          reaction.users.remove(user).catch(console.error);
          if (!canModifyQueue(member)) return message.channel.send("Vous devez d'abord rejoindre un salon vocal !");
          if (queue.playing) {
            queue.playing = !queue.playing;
            queue.connection.dispatcher.pause(true);
            queue.textChannel.send(`${user} ⏸ a mis en pause la musique.`).catch(console.error).then(msg => {
              msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
          });
          } else {
            queue.playing = !queue.playing;
            queue.connection.dispatcher.resume();
            queue.textChannel.send(`${user} ▶ a relancé la musique!`).catch(console.error).then(msg => {
              msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
          });
          }
          break;

        case "🔇":
          reaction.users.remove(user).catch(console.error);
          if (!canModifyQueue(member)) return message.channel.send("Vous devez d'abord rejoindre un salon vocal !");
          if (queue.volume <= 0) {
            queue.volume = 100;
            queue.connection.dispatcher.setVolumeLogarithmic(100 / 100);
            queue.textChannel.send(`${user} 🔊 a unmute la musique!`).catch(console.error).then(msg => {
              msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
          });
          } else {
            queue.volume = 0;
            queue.connection.dispatcher.setVolumeLogarithmic(0);
            queue.textChannel.send(`${user} 🔇 a mute la musique!`).catch(console.error).then(msg => {
              msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
          });
          }
          break;

        case "🔉":
          reaction.users.remove(user).catch(console.error);
          if (queue.volume == 0) return;
          if (!canModifyQueue(member)) return message.channel.send("Vous devez d'abord rejoindre un salon vocal !");
          if (queue.volume - 10 <= 0) queue.volume = 0;
          else queue.volume = queue.volume - 10;
          queue.connection.dispatcher.setVolumeLogarithmic(queue.volume / 100);
          queue.textChannel
            .send(`${user} 🔉 a diminué le volume, le volume est maintenant à ${queue.volume}%`)
            .catch(console.error)
            .then(msg => {
              msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
          });
          break;

        case "🔊":
          reaction.users.remove(user).catch(console.error);
          if (queue.volume == 100) return;
          if (!canModifyQueue(member)) return message.channel.send("Vous devez d'abord rejoindre un salon vocal !");
          if (queue.volume + 10 >= 100) queue.volume = 100;
          else queue.volume = queue.volume + 10;
          queue.connection.dispatcher.setVolumeLogarithmic(queue.volume / 100);
          queue.textChannel
            .send(`${user} 🔉 a augmenté le volume, le volume est maintenant à ${queue.volume}%`)
            .catch(console.error)
            .then(msg => {
              msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
          });
          break;

        case "🔁":
          reaction.users.remove(user).catch(console.error);
          if (!canModifyQueue(member)) return message.channel.send("Vous devez d'abord rejoindre un salon vocal !");
          queue.loop = !queue.loop;
          queue.textChannel
            .send(
                (`Le loop est maintenant ${queue.loop ? `**Actif**` : `**Inactif**`}`)
            )
            .catch(console.error)
            .then(msg => {
              msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
          });
          break;

        case "🔀":
          reaction.users.remove(user).catch(console.error);
          if (!canModifyQueue(member)) return message.channel.send("Vous devez d'abord rejoindre un salon vocal !");
          let songs = queue.songs;
          for (let i = songs.length - 1; i > 1; i--) {
            let j = 1 + Math.floor(Math.random() * i);
            [songs[i], songs[j]] = [songs[j], songs[i]];
          }
          
          queue.songs = songs;
          queue.textChannel
            .send(
                (`Lecture aléatoire de la liste de lecture 🔀`)
            )
            .catch(console.error)
            .then(msg => {
              msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
          });
          break;

        case "⏹":
          reaction.users.remove(user).catch(console.error);
          if (!canModifyQueue(member)) return message.channel.send("Vous devez d'abord rejoindre un salon vocal !");
          queue.songs = [];
          queue.textChannel.send(`${user} ⏹ a arrêté la musique!`)
          .catch(console.error)
          .then(msg => {
            msg.delete({ timeout: 5000 /*time unitl delete in milliseconds*/});
        });
          try {
            queue.connection.dispatcher.end();
          } catch (error) {
            console.error(error);
            queue.connection.disconnect();
          }
          collector.stop();
          break;

        default:
          reaction.users.remove(user).catch(console.error);
          break;
      }
    });

    collector.on("end", () => {
      playingMessage.reactions.removeAll().catch(console.error);
      if (PRUNING && playingMessage && !playingMessage.deleted) {
        playingMessage.delete({ timeout: 3000 }).catch(console.error);
      }
    });
  }
};
