var express = require('express');
var router = express.Router();
var async = require('async');
var logger = require('hibearnate-logger');
var liquidsoap = require('hibearnate-liquidsoap');

var thisRoute = 'Queue';

router.get('/', function(req, res) {
	req.route = thisRoute;
	logger.routeLog(req, "Starting");

	var command = 'request.queue';

	liquidsoap.getLiquidsoapData(command, function(responseData) {
		// one request in queue
		if (responseData.match(/^\d+$/)) {
			logger.routeLog(req, 'One request in queue');
			liquidsoap.getMetadata(responseData, function(metadata) {
				res.status(200).json(metadata);
				logger.routeLog(req, 'Complete');
			});
		}
		// multiple requests in queue
		else if (responseData.match(/^\d+\s+.*/)) {
			logger.routeLog(req, 'Multiple requests in queue');
			getMetadataForMany(responseData, function(responseJSON) {
				responseJSON.order = responseData.split(' ');
				res.status(200).json(responseJSON);
				logger.routeLog(req, 'Complete');
			});
		}
		// no requests in queue
		else {
			logger.routeLog(req, 'No requests in queue.');
			res.status(204).json({});
			logger.routeLog(req, 'Complete');
		}
	});
});

router.get('/:id', function(req, res) {
	ID = req.params.id;
	
	req.route = thisRoute + '/' + ID
	logger.routeLog(req, "Starting");

	liquidsoap.getMetadata(ID, function(metadata) {
		res.status(200).json(metadata);
		logger.routeLog(req, 'Complete');
	});
});
function getRequestTrace(id, callback) {
        command = 'request.trace ' + id;
        liquidsoap.getLiquidsoapData(command, function(traceData) {
                callback(traceData);
        })
}

function getMetadataForMany(rawIDs, callback) {
        var splitIDs = rawIDs.split(' ');
        var responseJSON = {};

        async.forEach(splitIDs, function(ID, callback) {
                liquidsoap.getMetadata(ID, function(metadata) {
                        responseJSON[ID] = metadata;
                        callback();
                });
        }, function() {
                callback(responseJSON);
        });
}


module.exports = router;
