'use strict';

var app;
var generator;
var seedText;

app = require('express')();
seedText = require('./lib/transcriptLoader');
generator = require('./lib/generator')(seedText);

/**
 * Builds a "success" response object.
 * @param   {*} content
 * @returns {object}
 */
function buildSuccessResponse(content) {
    return {
        success: true,
        content: content,
    };
}

/**
 * Builds an "error" response object.
 * @param   {*} error
 * @returns {object}
 */
function buildErrorResponse(error) {
    return {
        success: false,
        content: error,
    };
}

/**
 * Generates an arbitrary number of paragraphs.
 */
app.get('/:version/paragraphs', function (req, res) {
    var content;
    var count;

    // Default to 3 paragraphs.
    count = req.query.count || 3;
    content = generator.generateParagraphs(count);

    res.status(200).json(buildSuccessResponse(content));
});

/**
 * Generates an arbitrary number of sentences.
 */
app.get('/:version/sentences', function (req, res) {
    var content;
    var count;

    // Default to 3 sentences.
    count = req.query.count || 3;
    content = generator.generateSentences(count);

    res.status(200).json(buildSuccessResponse(content));
});

/**
 * Generates an arbitrary number of words.
 */
app.get('/:version/words', function (req, res) {
    var content;
    var count;

    // Default to 10 words.
    count = req.query.count || 10;
    content = [generator.generateWords(count)];

    res.status(200).json(buildSuccessResponse(content));
});

/**
 * Handles internal errors.
 */
app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).json(err.name + ' ' + err.message);
});

/**
 * Handles 404 errors.
 */
app.use(function(req, res, next) {
    res.status(404).json(buildErrorResponse('Unsupported endpoint'));
});

/**
 * Starts the server.
 */
app.listen(process.env.PORT, function () {
    console.log('Application started.');
});

@@ -1575,16 +1575,17 @@
 function
+ 
 (err, re
@@ -1590,30 +1590,24 @@
 req, res
-, next
 ) %7B%0A    
 console.
@@ -1602,87 +1602,121 @@
     
-console.error(err.stack);%0A    res.status(500).json(err.name + ' ' + err.message
+var content;%0A%0A    content = %5Berr.name + ' ' + err.message%5D;%0A%0A    res.status(500).json(buildErrorResponse(content)
 );%0A%7D
@@ -1766,16 +1766,17 @@
 function
+ 
 (req, re
@@ -1780,17 +1780,70 @@
  res
-, next) %7B
+) %7B%0A    var content;%0A%0A    content = %5B'Unsupported endpoint'%5D;%0A
 %0A   
@@ -1883,38 +1883,23 @@
 esponse(
-'Unsupported endpoi
+conte
 nt
-'
 ));%0A%7D);%0A

Return an array of content for errors.