// Simple persist middle ware
var path = require('path'),
    fs = require('fs');

var jsonFile = path.join(__dirname,"example-cinema.json");
var resetFile = path.join(__dirname,"example-cinema-src.json");

exports.middleware = function(req, res, next) {
    'use strict';

    if (req.url !== '/simple-persist') {
      return next();
    }

    res.setHeader('Content-Type', 'application/json; charset=utf-8');
    res.statusCode = 200;

    if(req.method === "PUT") {
      req.pipe(fs.createWriteStream(jsonFile));
      res.end(JSON.stringify({result: "OK"}));
    }
    else {
      var params = require('url').parse(req.url),
          readStream;
      if('reset' in params && params.reset) {
        readStream = fs.createReadStream(resetFile);
        readStream.pipe(fs.createWriteStream(jsonFile));
      }
      else {
        readStream = fs.createReadStream(jsonFile);
        readStream.on('error',function() {
          var srcFile = fs.createReadStream(resetFile);
          srcFile.pipe(fs.createWriteStream(jsonFile));
          srcFile.pipe(res);
        });
      }
      readStream.pipe(res);
    }
};
