/* global __dirname */
var express = require('express');
var events = require('events');
var fs = require('fs-extra');
var path = require('path');
var winston = require('winston');

var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

var pingbacker = new events.EventEmitter();

var pingbacks = [];

var logFilename = path.resolve(path.join(__dirname, '../../target/pingback-test-log', 'pingback-test.log'));

fs.mkdirsSync(path.dirname(logFilename));

if (fs.existsSync(logFilename)) {
    fs.unlinkSync(logFilename);
}

app.set('views', './views');
app.set('view engine', 'jade');

app.use(express.static(__dirname + '/public'));

app.get('/pingback/all', function (req, res) {
    res.render('pingbacks', { pingbacks: pingbacks });
});

app.get('/pingback', function (req, res) {
    var pingback = {
        date: new Date(),
        params: req.query
    };
    winston.info("Received pingback:", pingback.params);
    pingbacker.emit('pingback', pingback);
    res.status(204).end();
});

pingbacker.on('pingback', function (pingback) {
    pingbacks.push(pingback);
    // write ALL pingbacks to the log, this isn't efficient, but this code
    // is for testing only!
    fs.writeFileSync(logFilename, JSON.stringify(pingbacks));
});

io.on('connection', function (socket) {
    pingbacker.on('pingback', function (pingback) {
        socket.emit('pingbacks', [pingback]);
    });
});
server.listen(3000);
winston.info("Pingback test server ready on port 3000");
winston.info("Logging pingbacks to", logFilename);
