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

var jsonFilesBase = path.join(__dirname,"json/example-cinema");
var resetFilesBase = path.join(__dirname,"example-cinema-src");

function getJsonFile(key) {
  return jsonFilesBase + (key?("-" + key):"") + ".json";  
}

function getResetFile(key) {
  return resetFilesBase + (key?("-" + key):"") + ".json";
}

function createWriteStreamJson(file) {
  var dir = path.join(__dirname, 'json');
  if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
  }
  return fs.createWriteStream(file);
}

exports.middleware = function(req, res, next) {
    'use strict';
    
    var params = require('url').parse(req.url, true);

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

    var key = params.query.key;

    var jsonFile = getJsonFile(key);
    var resetFile = getResetFile(key);

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

    if(req.method === "PUT" || req.method === "POST") {
      req.pipe(createWriteStreamJson(jsonFile));
      setTimeout(function () {
    	  res.end(JSON.stringify({result: "OK"}));
      }, 3000);
    }
    else {
      var readStream;
      if('reset' in params.query && params.query.reset) {
        readStream = fs.createReadStream(resetFile);
        readStream.pipe(createWriteStreamJson(jsonFile));
      }
      else {
        readStream = fs.createReadStream(jsonFile);
        readStream.on('error',function() {
          var srcFile = fs.createReadStream(resetFile);
          srcFile.pipe(createWriteStreamJson(jsonFile));
          srcFile.pipe(res);
        });
      }
      readStream.pipe(res);
    }
};
