const { play } = require("../../Includes/play");
const ytdl = require("ytdl-core");
const YouTubeAPI = require("simple-youtube-api");
const { YOUTUBE_API_KEY, DEFAULT_VOLUME } = require("../../util/LanBot");
const youtube = new YouTubeAPI(YOUTUBE_API_KEY);
const { MessageEmbed } = require("discord.js");



const { MESSAGES } = require("../../util/constants");

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

    const serverQueue = message.client.queue.get(message.guild.id);
    if (!channel) return message.reply("Vous devez d'abord rejoindre un canal vocal!").catch(console.error);
    if (serverQueue && channel !== message.guild.me.voice.channel)
      return message
        .reply("Vous devez être dans le même canal que {user}", { user: message.client.user })
        .catch(console.error);

    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 !")
  
    const search = args.join(" ");
    const videoPattern = /^(https?:\/\/)?(www\.)?(m\.)?(youtube\.com|youtu\.?be)\/.+$/gi;
    const playlistPattern = /^.*(list=)([^#\&\?]*).*/gi;
    const url = args[0];
    const urlValid = videoPattern.test(args[0]);

    // Start the playlist if playlist url was provided
    if (!videoPattern.test(args[0]) && playlistPattern.test(args[0])) {
      return message.client.commands.get("playlist").execute(message, args);
    };


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

    let songInfo = null;
    let song = null;

    if (urlValid) {
      try {
        songInfo = await ytdl.getInfo(url);
        song = {
          title: songInfo.videoDetails.title,
          url: songInfo.videoDetails.video_url,
          duration: songInfo.videoDetails.lengthSeconds,
          views: songInfo.videoDetails.viewCount,
          thumbnail: songInfo.videoDetails.thumbnails[2]["url"]
        };
      } catch (error) {
        console.error(error);
        return message.reply(error.message).catch(console.error);
      }
    } else {
      try {
        const results = await youtube.searchVideos(search, 1, { part: "snippet" });
        songInfo = await ytdl.getInfo(results[0].url);
        song = {
          title: songInfo.videoDetails.title,
          url: songInfo.videoDetails.video_url,
          duration: songInfo.videoDetails.lengthSeconds,
          views: songInfo.videoDetails.viewCount,
          thumbnail: songInfo.videoDetails.thumbnails[2]["url"] 
        };
      } catch (error) {
        console.error(error);
        return message.reply(error.message).catch(console.error);
      }
    }
    var date = new Date(0);
    date.setSeconds(song.duration); // specify value for SECONDS here
    var timeString = date.toISOString().substr(11, 8);


    if (serverQueue) {
      serverQueue.songs.push(song);
      let embed = new MessageEmbed()
      .setTitle('Ajouté à la liste de lecture!')
      .setColor('#00fff1')
      .addField('Nom', song.title, true)
      .setThumbnail(song.thumbnail)
      .addField('Nombre de vues', song.views, true)
      .addField('Demandé par', message.author, true)
      .addField('Durée', timeString, true)
      return serverQueue.textChannel
        .send(embed)
        .catch(console.error);
    }

    queueConstruct.songs.push(song);
    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.PLAY;

