"use strict";

var Module = require("module");
var fs     = require("fs");

var FILENAME = ".roadrunner.json";
var data = {};

var wrap = function (fn) {
  return function (filename) {
    filename = filename || FILENAME;
    return fn(filename);
  };
};

var init = function () {
  Module._pathCache = exports.get("path");
  Module._realpathCache = exports.get("realpath");
};

exports.save = wrap(function (filename) {
  exports.set("realpath", Module._realpathCache);
  exports.set("path", Module._pathCache);

  fs.writeFileSync(filename, JSON.stringify(data, null, "  "));
});

exports.load = wrap(function (filename) {
  if (!fs.existsSync(filename)) return;

  try {
    data = JSON.parse(fs.readFileSync(filename));
  } catch (err) {
    return;
  }

  init();
});

exports.setup = wrap(function (filename) {
  var save = exports.save.bind(null, filename);
  process.on("exit", save);

  process.on("SIGINT", function sigint() {
    process.removeListener("SIGINT", sigint);
    save();
    process.kill(process.pid, "SIGINT");
  });
});

exports.reset = wrap(function (filename) {
  if (fs.existsSync(filename)) fs.unlinkSync(filename);

  data = {};

  init();
});

exports.get = function (key) {
  return data[key] = data[key] || {};
};

exports.set = function (key, val) {
  return data[key] = val;
};
