var Decoder = require('../..').Decoder
  , Encoder = require('../..').Encoder
  , Emitter = require('../..').Emitter
  , SyncFile = require('../..').SyncFile
  , fs = require('fs')
  , path = require('path');

function load(database, cb, err) {
  var file = 'test/fixtures/' + database
    , target = 'target/' + path.basename(database)
    , sync = 'target/' + path.basename(database, '.rdb') + '-sync.rdb';

    //console.dir(sync);

  var decoder = new Decoder({raw: false})
    , encoder = new Encoder()
    , objects = []
    , emitter = new Emitter({name: 'entry', passthrough: true})
    , input = new Buffer(0)
    , output = new Buffer(0)
    , syncOutput = new Buffer(0);

  emitter.on('entry', function onEntry(obj) {
    objects.push(obj);
  })

  decoder.on('load', function() {
    input = fs.readFileSync(file);
  })

  encoder.on('save', function() {

    // write to file synchronously
    var syncfile = new SyncFile(sync);
    for(var i = 0;i < objects.length;i++) {
      syncfile.write(objects[i]);
    }

    output = fs.readFileSync(target);
    syncOutput = fs.readFileSync(sync);
    cb(input, output, syncOutput);
  })

  if(err) {
    decoder.on('error', err);
  }

  decoder.load(file).pipe(emitter).pipe(encoder.save(target));
}

module.exports = load;
