"use strict";

const http = require('http');

const google = require('googleapis');
//const ytdl = require('ytdl-core');

const youtube = google.youtube('v3');

const apiKey = require('../google_api.json').apiKey;

const YOUTUBE_DL_SERVICE_HOSTNAME = process.env.YOUTUBE_DL_SERVICE_HOSTNAME || 'localhost';
const YOUTUBE_DL_SERVICE_PORT = process.env.YOUTUBE_DL_SERVICE_PORT || '5000';

function sortFormats(a, b) {
  // anything towards the beginning of the array is -1, 1 to move it to the end
  if (a.audioEncoding === 'opus' && b.audioEncoding !== 'opus') {
    return -1;
  } else if (a.audioEncoding !== 'opus' && b.audioEncoding === 'opus') {
    return 1;
  }

  if (a.audioEncoding === 'vorbis' && b.audioEncoding !== 'vorbis') {
    return -1;
  } else if (a.audioEncoding !== 'vorbis' && b.audioEncoding === 'vorbis') {
    return 1;
  }

  if (a.audioBitrate < b.audioBitrate) {
    return 1;
  } else if (a.audioBitrate > b.audioBitrate) {
    return -1;
  }

  return 0;
};

function formatTime(seconds) {
  function zeroPad(n) {
    return n < 10 ? '0' + n : n;
  };
  return Math.floor(seconds / 60) + ':' + zeroPad(seconds % 60);
};

/*
function fetchYoutubeInfo(url) {
  return new Promise((resolve, reject) => {
    ytdl.getInfo(url, { filter: 'audioonly' }, (err, info) => {
      if (err) {
        reject(err);
        return;
      }

      const formats = info.formats
        .filter(x => x.audioEncoding)
        .sort(sortFormats)
        .map(x => ({
          container: x.container,
          url: x.url,
          audioEncoding: x.audioEncoding,
          audioBitrate: x.audioBitrate,
        }));

      resolve([info, formats]);
    });
  });
};
*/
function fetchYoutubeInfo(url) {
  return new Promise((resolve, reject) => {
    const req = http.request({
      method: 'GET',
      hostname: YOUTUBE_DL_SERVICE_HOSTNAME,
      port: YOUTUBE_DL_SERVICE_PORT,
      path: '/download?v=' + url,
    }, (res) => {
      const buffers = [];

      res.on('error', (err) => {
        reject(err);
      });
      res.on('data', (chunk) => {
        buffers.push(chunk);
      });
      res.on('end', () => {
        const buf = Buffer.concat(buffers);
        const obj = JSON.parse(buf);
        resolve(obj);
      });
    });

    req.end();
  });
}

function searchYoutube(searchString) {
  return new Promise((resolve, reject) => {
    youtube.search.list({ key: apiKey, part: 'snippet', q: searchString, maxResults: 10 }, (err, results) => {
      if (err) {
        return reject(err);
      }
      resolve(results);
    });
  });
};

module.exports = {
  sortFormats,
  formatTime,
  fetchYoutubeInfo,
  searchYoutube,
};

@@ -380,16 +380,181 @@
 5000';%0A%0A
+function formatTime(seconds) %7B%0A  function zeroPad(n) %7B%0A    return n %3C 10 ? '0' + n : n;%0A  %7D;%0A  return Math.floor(seconds / 60) + ':' + zeroPad(seconds %25 60);%0A%7D;%0A%0A/*%0A
 function
@@ -574,16 +574,16 @@
 a, b) %7B%0A
-
   // any
@@ -1151,173 +1151,8 @@
 %7D;%0A%0A
-function formatTime(seconds) %7B%0A  function zeroPad(n) %7B%0A    return n %3C 10 ? '0' + n : n;%0A  %7D;%0A  return Math.floor(seconds / 60) + ':' + zeroPad(seconds %25 60);%0A%7D;%0A%0A/*%0A
 func
@@ -2171,24 +2171,64 @@
 t(buffers);%0A
+        if (res.statusCode === 200) %7B%0A  
         cons
@@ -2256,24 +2256,26 @@
 f);%0A        
+  
 resolve(obj)
@@ -2276,16 +2276,77 @@
 e(obj);%0A
+        %7D else %7B%0A          reject(%60Failed request: $%7Bbuf%7D%60);%0A
       %7D)
@@ -2688,16 +2688,18 @@
 rts = %7B%0A
+//
   sortFo

check YTDL API response code