/**
 *	File: app/radio.js
 *	Author: Gerrit Linnemann
 *	
 *	Where the magic happens.
 */


// load the things we need
var spawn = require('child_process').spawn;
var exec  = require('child_process').exec;
var fs    = require("fs");
var http  = require('http');
var wget  = require('wget');


var App = null;
var Log = null
var Helper = null;
var Conf = null;

var Child = null;


exports.init = function(Express, Configuration) {
	App = Express;
	Conf = Configuration;
	Log = App.get('Log');
	Helper = App.get('Helper');
	
	Log.debug('Radio: ' + exports.countChannels() + ' channels configured');
	Helper.each(Conf.channels, function(channel, isLast) {
  	//Log.inspect('Channel', channel);
  	Log.log('Radio: Found channel ' + channel.title);
	});
	
	return this;
}

exports.countChannels = function() {
  return Conf.channels.length;
}

exports.getChannels = function() {
  return Conf.channels;
}

exports.getChannel = function(idx) {
  if(Helper.isDefinedAndNotNull(Conf.channels[idx])) {
    return Conf.channels[idx];
  } else {
    return null;
  }
}

exports.play = function(idx) {
  var channel = Conf.channels[idx];
  if(channel !== undefined) {
    var stream2play = channel.stream;
    var m3u = '/tmp/kitchenradio.m3u';
    
    try {
      fs.unlinkSync(m3u);
    } catch(e) {
      Log.error('Radio: Error deleting "' + m3u + '".' + e);
    }
    
    var download = wget.download(channel.stream, m3u);    
    download.on('end', function(output) {
      Log.inspect('Radio: Download completed', output);
    
      if(Helper.isDefinedAndNotNull(Child)) {
        // kill active instances
        try {
          Child.kill();
        } catch(err) {
          Log.error('Radio: Error killing process');
        }
      }
      
      var catCmd = 'cat ' + m3u + ' | grep http://';
      exec(catCmd, function(error, stdout, stderr){
        Log.inspect('Radio: Play', data);
      });
      
  
      /*try {
        var parsers = require('playlist-parser');
        var M3U = parsers.M3U;
  
        var playlist = M3U.parse(fs.readFileSync(m3u, { encoding: 'utf8' }));
        Log.inspect('Radio: playlist', playlist);
  
        if(Helper.isDefinedAndNotNull(playlist[0])) {
          stream2play = playlist[0].file;
        } else {
          
        }
      } catch(e) {
        Log.error(e);
      }*/

      var Child = spawn(
        'mplayer',
        [
          '-slave',
          '-quiet',
          stream2play
        ]
      );

      // listen for any response from the child
      Child.stdout.on('data', function(chunk) {
        Log.log('Radio: stdout: ' + chunk);
      });

      // listen for any errors
      Child.stderr.on('data', function (chunk) {
        Log.error('Radio: stderr: ' + chunk);
      });

      /*Child.on('exit', function (code){
        Log.log('Radio: Child process exited with exit code ' + code);
      });*/
    });
    
    download.on('error', function(err) {
      Log.error('Radio: Error downloading playlist. ' + err);
    });
  } else {
    Log.error('Radio: No channel defined!');
  }
}