/*
 Index pages:
 https://teamrock.com/radio/show/the-school-of-rock
 https://teamrock.com/radio/show/the-metal-hammer-magazine-show#
 https://teamrock.com/radio/show/the-classic-rock-magazine-show
 */

var request = require('request');
var cheerio = require('cheerio');
var STRING = require('string');
var logger = require('log4js').getLogger();
var Events = require('events');
var jsonfile = require('jsonfile');
var fs = require('fs');
var cron = require('node-cron');

//var root = 'http://teamrock.com';

var root = 'http://localhost:9000';
var wantedType = ['audio/mpeg'];

var eventHandler = new Events();

var rssJsonFile = __dirname + '/' + 'rr-rss.json';

module.exports = {
  rssJsonFile : __dirname + '/' + 'rr-rss.json',
  rssJson:{},
  getPage: function(indexfile) {
    logger.debug('getPage');
    var url = root + indexfile;
    logger.debug(url);
    logger.info(indexfile);

    return new Promise(function(resolve, reject) {
      'use strict';
var rssBlob = {};

      request(url, function(err, resp, body) {
        if (err) {
          //  Logger.error(err);
          return reject(err);
          // Throw err;
        }

        var $ = cheerio.load(body);
        var audioblock = $('AUDIO');

        audioblock.find('SOURCE').each(function(div) {

          var s = $(this).attr('type');

          if (wantedType.indexOf(s) !== -1) {
            var f = $(this).attr('src');
            var suffix = f.substr(f.lastIndexOf('.') + 1, f.length);

            if (suffix === 'mp3') {
              rssBlob.file = f;
            }
          }

        });

        var sectionHead = $('H2.section-title').text();

        logger.debug(sectionHead);

        return resolve(rssBlob);
      }, function(error, response, body) {
        if (response.statusCode !== 200) {
          logger.error(response.statusCode);
          logger.error(body);
          return reject(error);
        }
      });
    });

  }, getIndexPage: function() {

    var url, self = this;

    url = 'http://localhost:9000/the-school-of-rock';

    return new Promise(function(resolve, reject) {
      'use strict';

      request(url, function(err, resp, body) {
        if (err) {
          //  Logger.error(err);
          return reject(err);
          // Throw err;
        }

        var $ = cheerio.load(body);
        var playlistBody = $('div.my-playlist');

        var queue = [];

        playlistBody.find('a.my-playlist-item').each(function(div) {

          var s = $(this).attr('href');
          if (self.rssJson.masterindex.indexOf(s) === -1) {
            queue.push(s);
          }

        });

        return resolve(queue);
      }, function(error, response, body) {
        if (response.statusCode !== 200) {
          logger.error(response.statusCode);
          logger.error(body);
          return reject(error);
        }
      });
    });

  },
  doUpdateEntry: function(d) {
    logger.debug('Updatefile:', d);
},
doUpdateQueue: function(queue) {
    'use strict';
    logger.info('Update queue');
    logger.debug(queue);
    for(var t=0;t<queue.length;t++)
    {
     // this.rssJson.queue.push(queue[t]);
      eventHandler.emit('updateEntry', queue[t]);
    }
    //logger.debug(this.rssJson);

  }
, loadMainIndex: function() {
    jsonfile.readFile(rssJsonFile, function(err, obj) {
          if (err) {

            logger.warn('Creating...');
            logger.debug(module.exports.rssJson);

            module.exports.rssJson = {title:'Team Rock Radio',
              description:'Team Rock Radio',
            link:'',
            pubDate:'',
            language:'en-us',
            items:[], masterindex:[],queue:[]};
            logger.debug(module.exports.rssJson);
          }
          else {
            logger.info('RSS Data loaded...');
            module.exports.rssJson = obj;
          }

        });


} };


var doUpdateQueue = (q) => {
  module.exports.doUpdateQueue(q);
};

var doUpdateEntry = (q) => {
  module.exports.getPage(q);
};

eventHandler.on('updateQueue', doUpdateQueue);
eventHandler.on('updateEntry', doUpdateEntry);

module.exports.loadMainIndex();





setTimeout(function() {
  module.exports.getIndexPage()
            .then((d)=> {
              logger.warn(d);
              eventHandler.emit('updateQueue', d);
            })
            .catch((e) => {
              logger.error(e);
            });

}, 5000);
