/* global exports, require */
var db = require('../db/polls');

function convertRelUrlToAbs(req, relativeUrl) {
    return req.protocol + '://' + req.headers.host + relativeUrl;
}

function sendPollNotFoundError(req, res) {
    res.format({
        'application/json': function() {
            res.statusCode = 404;
            res.send({
                type: convertRelUrlToAbs(req, '/errors/poll-not-found'),
                title: 'Poll not found'
            });
        }
    });
}

exports.__convertRelUrlToAbs = convertRelUrlToAbs;

exports.index = function(req, res) {
    res.format({
        'application/json': function() {
            res.send(db.getPolls());
        }
    });
};

exports.get = function(req, res) {
    var poll = db.getPoll(req.param('pollId'));
    if(!poll) {
        sendPollNotFoundError(req, res);
    } else {
        res.format({
            'application/json': function() {
                res.send(poll);
            }
        });
    }
};

exports.put = function(req, res) {
    var poll = db.getPoll(req.param('pollId'));
    if(!poll) {
        sendPollNotFoundError(req, res);
    } else {
        db.updatePoll(req.param('pollId'), req.body);
        res.statusCode = 204;
        res.send();
    }
};

exports.del = function(req, res) {
    var poll = db.getPoll(req.param('pollId'));
    if(!poll) {
        sendPollNotFoundError(req, res);
    } else {
        db.deletePoll(req.param('pollId'));
        res.statusCode = 204;
        res.send();
    }
};

@@ -482,16 +482,218 @@
  %7D);%0A%7D%0A%0A
+function resourceOperation(req, res, operation) %7B%0A    var poll = db.getPoll(req.param('pollId'));%0A    if(!poll) %7B%0A        sendPollNotFoundError(req, res);%0A    %7D else %7B%0A        operation(poll);%0A    %7D%0A%7D%0A%0A
 exports.
@@ -933,119 +933,50 @@
     
-var poll = db.getPoll(req.param('pollId'));%0A    if(!poll) %7B%0A        sendPollNotFoundError(req, res);%0A    %7D else
+resourceOperation(req, res, function(poll)
  %7B%0A 
@@ -1095,32 +1095,34 @@
        %7D);%0A    %7D
+);
 %0A%7D;%0A%0Aexports.put
@@ -1153,119 +1153,46 @@
     
-var poll = db.getPoll(req.param('pollId'));%0A    if(!poll) %7B%0A        sendPollNotFoundError(req, res);%0A    %7D else
+resourceOperation(req, res, function()
  %7B%0A 
@@ -1295,24 +1295,26 @@
 end();%0A    %7D
+);
 %0A%7D;%0A%0Aexports
@@ -1349,119 +1349,46 @@
     
-var poll = db.getPoll(req.param('pollId'));%0A    if(!poll) %7B%0A        sendPollNotFoundError(req, res);%0A    %7D else
+resourceOperation(req, res, function()
  %7B%0A 
@@ -1480,17 +1480,19 @@
 send();%0A
-
     %7D
+);
 %0A%7D;%0A

Extract common resource operation logic