var fs = require('fs');
var youtubedl = require('youtube-dl');
var db = require("../database/mongo");




function run() {
    //setInterval(getTheData, 3000);
    console.log("run");
    setInterval(getKhanVideos, 300000);
};

//getData();

run();
//getKhanVideos();


function getKhanVideos()
{

    console.log("get Khan Videos");
    //db.khanitems.find({youtube_id:{$not:{$in:[null,'0']}},processed:0},{youtube_id:1}).limit(100,function(err,data){
        //db.khanitems.find({processed:0, path:/cience/},{youtube_id:1}).limit(100,function(err,data){
    db.khanitems.find({processed :0,youtube_id:{$ne:null}},{youtube_id:1}).limit(100,function(err,data){
        if(!err)
        {
            for(i=0;i<data.length;i++){
                var youtube_id = data[i].youtube_id;
                console.log(youtube_id);
                if(youtube_id != null && youtube_id != "0")
                {
                    console.log("call Download");
                    download(youtube_id,i);
                }
                else{
                    db.khanitems.update({youtube_id:data[i].youtube_id},{$set:{processed:3}},{w:1,multi:true}); 
                    console.log("updated null")  
                }

                

            }
        }
    })
}




 function download(video_id,i)
 {
    var video = youtubedl('http://www.youtube.com/watch?v='+video_id,
    // Optional arguments passed to youtube-dl.
    ['--format=18'],
    // Additional options can be given for calling `child_process.execFile()`.
    { cwd: __dirname });
   
  // Will be called when the download starts.
  video.on('info', function(info) {
    console.log('Download started');
    console.log('filename: ' + info._filename);
    db.khanfilename.insert({filename:info._filename,youtube_id:video_id});
    console.log('size: ' + info.size);
  });
   
  video.pipe(fs.createWriteStream('/var/www/html/tutor/videos/'+video_id+'.mp4').on('finish', function(_file){
      //console.log(fs);
      //console.log(" -----  "+fs._filename + " ------");
      //console.log('file downloaded to ', '/tmp/imageresize/'+x);
    }));

    var filename = "";
  
  video.on('complete', function complete(info) {
      'use strict';
      console.log('filename: ' + info._filename + ' already downloaded.');
    });
     
    video.on('end', function complete(info) {
        //console.log(info);
      console.log(' finished downloading! '+ video_id + "  ::: " + i);
      db.khanitems.update({youtube_id:video_id},{$set:{processed:1}});      
    });

    video.on('error',function(err){
        console.log('An error occured');
        console.log(err);      
        db.khanitems.update({youtube_id:video_id},{$set:{processed:2}});      
    })



 }; 