const { MESSAGES } = require("../../util/constants");
const { MessageEmbed } = require("discord.js");
const { play } = require("../../Includes/play");
const YouTubeAPI = require("simple-youtube-api");

const {
  YOUTUBE_API_KEY,
  MAX_PLAYLIST_SIZE,
  DEFAULT_VOLUME,
} = require("../../util/LanBot");
const youtube = new YouTubeAPI(YOUTUBE_API_KEY);


module.exports.run = async (client, message, args, settings) => {
  const { channel } = message.member.voice;
    const serverQueue = message.client.queue.get(message.guild.id);

    if (!channel.permissionsFor(message.client.user).has("CONNECT")) return message.channel.send("Je n'ai pas la permission de rejoindre un salon vocal !")
    if (!channel.permissionsFor(message.client.user).has("SPEAK"))return message.channel.send("Je n'ai pas la permission Parler dans le salon vocal !")

    if (serverQueue && channel !== message.guild.me.voice.channel)
      return message
        .reply(`Vous devez être dans le même canal que ${message.client.user}`)
        .catch(console.error);

    const search = args.join(" ");
    const pattern = /^.*(youtu.be\/|list=)([^#\&\?]*).*/gi;
    const url = args[0];
    const urlValid = pattern.test(args[0]);

    const queueConstruct = {
      textChannel: message.channel,
      channel,
      connection: null,
      songs: [],
      loop: false,
      volume: DEFAULT_VOLUME || 100,
      playing: true
    };

    let playlist = null;
    let videos = [];

    if (urlValid) {
      try {
        playlist = await youtube.getPlaylist(url, { part: "snippet" });
        videos = await playlist.getVideos(MAX_PLAYLIST_SIZE || 10, { part: "snippet" });
      } catch (error) {
        console.error(error);
        return message.reply("Playlist introuvable ! 🥺 ").catch(console.error);
      }
    } else {
      try {
        const results = await youtube.searchPlaylists(search, 1, { part: "snippet" });
        playlist = results[0];
        videos = await playlist.getVideos(MAX_PLAYLIST_SIZE || 10, { part: "snippet" });
      } catch (error) {
        console.error(error);
        return message.reply(error.message).catch(console.error);
      }
    }

    const newSongs = videos
      .filter((video) => video.title != "Private video" && video.title != "Deleted video")
      .map((video) => {
        return (song = {
          title: video.title,
          url: video.url,
          duration: video.durationSeconds
        });
      });

    serverQueue ? serverQueue.songs.push(...newSongs) : queueConstruct.songs.push(...newSongs);

    let playlistEmbed = new MessageEmbed()
      .setTitle(`${playlist.title}`)
      .setDescription(newSongs.map((song, index) => `${index + 1}. ${song.title}`))
      .setURL(playlist.url)
      .setColor("#F8AA2A")
      .setTimestamp();

    if (playlistEmbed.description.length >= 2048)
      playlistEmbed.description =
        playlistEmbed.description.substr(0, 2007) + ("\nListe de lecture supérieure à la limite de caractères...");

    message.channel.send((`${message.author} a commencé une playlist`), playlistEmbed);

    if (!serverQueue) {
      message.client.queue.set(message.guild.id, queueConstruct);

      try {
        queueConstruct.connection = await channel.join();
        await queueConstruct.connection.voice.setSelfDeaf(true);
        play(queueConstruct.songs[0], message);
      } catch (error) {
        console.error(error);
        message.client.queue.delete(message.guild.id);
        await channel.leave();
        return message.channel.send(`Impossible de rejoindre le channel: ${error}`).catch(console.error);
      }
    }
};

module.exports.help = MESSAGES.COMMANDS.MUSIQUE.PLAYLIST;

/*
Play Pause      ⏯️
Stop            ⏹️
Shuffle         🔀
Loop All        🔁
Loop One        🔂

*/

