const { spawn } = require('child_process');
const ipcMain = require('electron').ipcMain;
const dl_routine = require('./youtube-dl.routine')

const web = require('./webLoader/router');

const pot = require('./player_onTop');
const folderWatchr = require('./watchr')
console.log(global.dir);

var orig_path = "";
var path = "";
var format = "mp3";
var fol = null;

var pot_open_ev = null;
ipcMain
.on('start-download', (event, arg)=>{
  path = orig_path
  var download = new yt_dl(arg.url,arg.id);
  download.addListen(event)
  download.download();
})
.on('set-format',(event,arg)=>{
    format = arg.format;
})
.on('start-download-pl', (event, arg)=>{
    var mkdirp = require('mkdirp');
    if(orig_path === ""){
        path = '.'
    }else{
        path = orig_path
    }
    mkdirp(path+'/'+arg.folder, function(err) {
        path = path+'/'+arg.folder;
        // path exists unless there was an error
        var download = new yt_dl(arg.url,arg.id);
        download.addListen(event)
        download.download();
    });
})
.on('setPath', function(event, arg) {
  path = arg.path;
  orig_path = arg.path;
  if(fol !== null){
      fol.destroy()
  }
  fol = new folderWatchr(path);
  console.log('SET Path: '+path)
});

var yt_dl = class{
    constructor(url,id){
        this.url = url ;
        this.percent = 0;
        this.lwrite = null;
        this.id = id;
    }
    addListen(e){
        this.lwrite = e
    }
    status(stat){
        this.lwrite('download-progress', stat);
    }
    download(){
        var log = [];
        var me = this;
        var ls;

        var m = dl_routine(path,this.url,format);
        ls = spawn(m[0],m[1]);
        if(path == ''){
            //ls = spawn(global.dir+'/lib/youtube-dl', ['-x','--audio-format','mp3','-i',this.url]);
        }else{
            //ls = spawn(global.dir+'/lib/youtube-dl', ['-x','--audio-format','mp3','-i',this.url,'-o',path+'/%(title)s.%(ext)s']);
        }

        ls.stdout.on('data', (data) => {
            data = data.toString('utf8');
            log.push(data);
          //console.log(data);
          try{
              var z = data.replace(/(\r\n|\n|\r)/gm,"").split(' ');
              console.log(z)
              switch (z[0]) {
                  case '[download]':
                      var percent = data.split(']')[1].split('of')[0];
                      //console.log(z)
                      me.percent = percent.trim();
                      me.lwrite.sender.send('download-progress',{percent :me.percent,id:me.id});
                      break;
                  default:
              }
              var m = z.length;
              for(var i = 0;i<m;i++){
                  if(z[i] === '[ffmpeg]'){
                      if(z[i+1] === 'Merging'){
                          var file = "";
                          for(var x = i+4;x<m;x++){
                              console.log(z[x])
                              if(z[x] === 'has' && z[x+1] === "already" && z[x+2] === "been" && z[x+3] === 'downloaded'){
                                  break;
                              }
                              file = z[x];
                          }
                          me.lwrite.sender.send('file',{id:me.id,file:file});
                          break;
                      }
                  }
              }
          }catch(e){
              console.log(e);
          }finally{

          }
        });
        ls.stderr.on('data', (data) => {
          console.log(`stderr: ${data}`);
        });
        ls.on('close', (code) => {
          console.log(`child process exited with code ${code}`);
          me.lwrite.sender.send('file',{id:me.id,file:log[log.length-2].split('[ffmpeg] Destination: ')[1]});
          me.lwrite.sender.send('process-fin',{percent :me.percent,id:me.id});
        });
    }
}

module.exports = yt_dl;
