// https://github.com/garbados/mocha_nock_demo/blob/master/test/record.js

var nock = require('nock');
var path = require('path');
var fs = require('fs');

module.exports = function(name, filters) {
  var tape = path.join(__dirname + '/../fixtures/' + name + '.js');
  var has_fixtures = !!process.env.NOCK_RECORD;

  return {
    play: function() {
      if(!has_fixtures) try {
        require(tape);
        has_fixtures = true;
      } catch (e) {
        nock.recorder.rec({
          dont_print: true
        });
      } else {
        has_fixtures = false;
        nock.recorder.rec({
          dont_print: true
        });
      }
    },

    stop: function(done) {
      if(!has_fixtures) {
        var fixtures = nock.recorder.play();
        var text = "var nock = require('nock');\n" + fixtures.join('\n');
        if(typeof filters !== 'undefined' && filters !== null) {
          filters.forEach(function(filter, index) {
            text = text.replace(new RegExp(filter.from, 'g'), filter.to);
          });
        }
        fs.writeFile(tape, text, function() {
          if(done) done();
        });
      } else {
        if(done) done();
      }
    }
  }
};

