'use strict';

var birtConfig = config.get('birt'),
    utilHttpStatus =  require('../../shared/utils/UtilHttpStatus'),
    request = require('request'),
    q = require('q');

var checkServer = function() {
    var deferred = q.defer();

    var url = 'http://' + birtConfig.server + ':' + birtConfig.port;
    request.get(url, function (err, response) {
        if (!err && response.statusCode === 200) {
            deferred.resolve('Birt server running!');
        } else {
            var errorMsg = 'Birt server connection failed with error: ' + err;
            logger.error(errorMsg);
            deferred.reject(errorMsg);
        }
    });

    return deferred.promise;
};

exports.viewReport = function(req, res) {

    var query = req.query;
    var params = '';
    for(var key in query) {
        params += '&' + key + '=' + query[key];
    }

    checkServer().then(function success(){
        var url = 'http://' + birtConfig.server + ':'
            + birtConfig.port + '/' + birtConfig.basePath + '/preview?' + params;

        request.get(url, function (err, response, body) {}).pipe(res);
    }, function error(err) {
        res.status(utilHttpStatus.INTERNAL_SERVER_ERROR).send(err).end();
    });

};