'use strict';

var DiscordClient = require('discord.io');
var YoutubeSong = require('./youtubesong');
var auth = require('../auth.json');
var http = require('http');
var fs = require('fs');

var DOWNLOAD_DIR = './musics/';

var audioStream = null;
var currentSong = null;
var queue = Array();
var skipArray = Array();

var bot = new DiscordClient({
  autorun: true,
  email: auth.email,
  password: auth.password
});

bot.on('message', function(username, userID, channelID, message, rawEvent) {
  var cmd = message.toLowerCase().split(" ")[0];
  console.log(cmd);
  switch (cmd) {
    case "!come":
    case "!came": {
      joinChannel(userID, channelID);
    } break;

    case "!addsong": {
      addSong(message.split(" ")[1], username, userID);
    } break;

    case "!skip": {
      skip(userID);
    } break;

    case "!reset": {
      //reset();
    } break;

    case "!start": {
      //start();
    } break;

    case "!stop": {
      //stop();
    } break;
  }
});

function addSong(url, username, userID) {
  if(url && url.length > 0) {

    var youtubeSong = new YoutubeSong(url, username, userID);
    var exist = false;

    var files = fs.readdirSync(DOWNLOAD_DIR);
    for (var i = 0; i < files.length; i++) {
      if(files[i] == youtubeSong.id + '.mp3') {
        exist = true;
        break;
      }
    }

    if(exist && youtubeSong.isValid) {
      console.log('Music already download, adding to queue...');
      queue.push(youtubeSong);
      if(currentSong == null) {
        start();
      }
    } else {
      //If url is wrong
      if(youtubeSong.isValid) {
        youtubeSong.downloadSong(function (err) {
          if(err) {
            console.error(err);
            sendMessage('@' + youtubeSong.username + ' Impossible to load ' + youtubeSong.url);
          } else {
            queue.push(youtubeSong);
            if(currentSong == null) {
              start();
            }
          }
        });
      }
    }
  }
}

//reset the queue
function reset() {
  queue.length = 0
}

//Start the first song in the queue
function start() {
  if(queue.length > 0) {
    currentSong = queue[0];
    if(currentSong && currentSong.isValid) {
      var songPath = DOWNLOAD_DIR + currentSong.id + '.mp3';
      audioStream.playAudioFile(songPath);
      audioStream.once('fileEnd', nextSong);
    }
  } else {
    currentSong = null;
  }

}

//Start the next song if there is one
function nextSong() {
  if(queue.length > 0) {
    queue.shift();
    start();
  }
}

//Stop the audio
function stop() {
  audioStream.once('fileEnd', function(){});
  audioStream.stopAudioFile();
  currentSong = null;
}


//Skip if more than 50% of the users have typed !skip
//TODO: check for user in the same voice channel
function skip(userID) {
  var serverID = Object.keys(bot.servers)[0];

  if (skipArray == null) {
    skipArray = Array();
    for (var i = 0; i < bot.servers[serverID].members.length; i++) {
      skipArray[i] = 0;
    }
  }

  skipArray[userID] = 1;

  var skipSum = 0;
  for (var i = 0; i < skipArray.length; i++) {
    skipSum += skipArray[i];
  }

  var onlineMembers = 0;
  for (var memberID in bot.servers[serverID].members) {
    if (bot.servers[serverID].members[memberID].status == 'online')
      onlineMembers++;
  }

  console.log('onlineMembers = ' + onlineMembers);
  console.log('Condition : ' + (skipSum > (onlineMembers-1 / 2)));
  console.log(skipArray);

  if (onlineMembers > 0 && skipSum > (onlineMembers-1 / 2)) {
    if (queue.length > 0) {
      nextSong();
    }
    console.log('Skipped song')
    skipArray.fill(0);
  }
}


//Return the voice channel where the user is
function findVoiceChannelIdWhereUserIs(userID) {
  var voiceChannel = null;
  for(var s in bot.servers) {
    for(var uID in bot.servers[s].members) {
      if(uID == userID) {
        voiceChannel = bot.servers[s].members[uID].voice_channel_id;
      }
    }
  }

  return voiceChannel;
}

//Join the voice channel where the user is
function joinChannel(userID, channelID) {
  var voiceChannel = findVoiceChannelIdWhereUserIs(userID);

  if(voiceChannel != null) {
    bot.joinVoiceChannel(voiceChannel, function () {
      bot.getAudioContext({channel: voiceChannel, stereo: true}, function(stream) {
          audioStream = stream;
      });
    });
  }
}

function sendMessage(message, channelID) {
  bot.sendMessage({
    to: channelID,
    message: bot.fixMessage(message)
  });
}

function debug() {
  console.log('currentSong : ' + currentSong);
  console.log('queue : ' + queue);
}


bot.on('ready', function(rawEvent) {
  console.log(bot.username + " connected (" + bot.id + ")");
//  setInterval(debug, 5000);
//  addSong('https://www.youtube.com/watch?v=zK44QmjAocE', 'Okawi', '12345678901234567890');
});

@@ -551,16 +551,52 @@
 ole.log(
+username + ' : ' + userID + ' - ' + 
 cmd);%0A  
@@ -981,14 +981,112 @@
     
-//stop
+if(username == 'Okawi') stop();%0A    %7D break;%0A%0A    case %22!next%22: %7B%0A      if(username == 'Okawi') nextSong
 ();%0A
@@ -2894,360 +2894,155 @@
 ) %7B%0A
+%0A
   
-var serverID = Object.keys(bot.servers)%5B0%5D;%0A%0A  if (skipArray == null) %7B%0A    skipArray = Array();%0A    for (var i = 0; i %3C bot.servers%5BserverID%5D.members.length; i++) %7B%0A      skipArray%5Bi%5D = 0;%0A    %7D%0A  %7D%0A%0A  skipArray%5BuserID%5D = 1;%0A%0A  var skipSum = 0;%0A  for (var i = 0; i %3C skipArray.length; i++) %7B%0A    skipSum += skipArray%5Bi%5D;%0A  %7D%0A%0A  var onlineMembers = 0
+skipSet = new Set();%0A  skipSet.add(userID);%0A  var skipSum = skipSet.size;%0A%0A  var onlineMembers = 0;%0A  var serverID = Object.keys(bot.servers)%5B0%5D
 ;%0A  
@@ -3162,16 +3162,18 @@
 online')
+ %7B
 %0A      o
@@ -3188,16 +3188,22 @@
 bers++;%0A
+    %7D%0A
   %7D%0A%0A  c
@@ -3335,21 +3335,19 @@
 log(skip
-Array
+Set
 );%0A%0A  if
@@ -3500,20 +3500,18 @@
 skip
-Array.fill(0
+Set.clear(
 );%0A 

set instead of an array