const request = require('request');
const fs      = require('fs')
const ipcMain = require('electron').ipcMain;
const unzip   = require('unzip')


var libsx = {
    "ffmpeg":"ffmpeg",
    "ffplay":"ffplay",
    "ffprobe":"ffprobe",
    "youtube-dl":"youtube-dl"
}
var libs = {};

libs.listen = null;
libs.libs = null;
ipcMain
.on('download-lib', (event, arg)=>{
  console.log('TEST')
  libs.listen = event;
  console.log(`This platform is ${process.platform}`);
  switch (process.platform) {
      case "win32":
          for (var lib in libsx) {
              libsx[lib] = libsx[lib]+'.exe';
          }
          break;
      default:
  }
  for (var lib in libsx) {
      if (fs.existsSync(global.dir+"/lib/"+libsx[lib])) {

      }else{
          libsx[lib] = null;
      }
  }
  libs.libs = libsx;
  if(libsx['ffmpeg'] === null || libsx['ffplay'] === null || libsx['ffprobe'] === null ){
      var z = 0;
      var url = libs.ff(process.platform);
      if(url === ''){
        libs.checkNext('youtube-dl');
      }else{
        libs.download(url,"ffmpeg",function(data,file){
            fs.createReadStream(file)
            .pipe(unzip.Parse())
            .on('entry', function (entry) {
              var fileName = entry.path;
              var type = entry.type; // 'Directory' or 'File'
              var size = entry.size;
              console.log(fileName)
              if (fileName === "ffmpeg-latest-win32-static/bin/ffmpeg.exe" || fileName === "ffmpeg-latest-win32-static/bin/ffprobe.exe" ||  fileName === "ffmpeg-latest-win32-static/bin/ffplay.exe") {
                entry.pipe(fs.createWriteStream(global.dir+'/lib/'+fileName.split('/')[2]));
                console.log('TEST')
                z++;
                if(z == 3){
                    libs.checkNext('youtube-dl');
                }
              } else {
                entry.autodrain();
              }
            });
        });
      }
  }else{
      libs.checkNext('youtube-dl');
  }
  console.dir(libsx);
})
libs.checkNext = (nxt)=>{
    if(  libs.libs['youtube-dl'] === null ){
        libs.yt_dl(process.platform,function(){
            libs.startFull();
        });
    }else{
        libs.startFull();
    }
}
libs.startFull = ()=>{
    libs.listen.sender.send('fin-loading',{});
}
libs.ff = (os)=>{
    var url = "";
    switch (os) {
        case "win32":
            url = 'http://ffmpeg.zeranoe.com/builds/win32/static/ffmpeg-latest-win32-static.zip';
            break;
        case "linux":
            url = ''
          
        default:

    }
    return url;
}
libs.yt_dl = (os,cb)=>{
    var url = "";
    switch (os) {
        case "win32":
            url = 'https://yt-dl.org/downloads/2017.08.13/youtube-dl.exe';
            libs.download(url,"youtube-dl",function(data,file){
                fs.renameSync(file,global.dir+'/lib/youtube-dl.exe');
                cb();
            })
            break;
        case "linux":
            url = ''
            cb();
        default:
          
    }
    

}
libs.download = (url,data,cb)=>{
    var r = request(url);
    var actual = 1;
    var  full = 100;
    var perc = 0;
    r.on('data', function (chunk) {
        actual += chunk.length;
        perc = actual / full * 100;
        console.log(perc);
        libs.listen.sender.send('progress',{percent :Math.floor(perc)});
    });

    r.on('response',  function (res) {
      res.pipe(fs.createWriteStream(global.dir+'/tmp/' + data + '.' + res.headers['content-type'].split('/')[1]));
      full =  res.headers[ 'content-length' ] ;
      res.on('end', function () {
         cb(data,global.dir+'/tmp/' + data + '.' + res.headers['content-type'].split('/')[1]);
      })
    });
}



module.exports = libs;
