/*
 * The MIT License
 *
 * Copyright (c) 2016 Juan Cruz Viotti. https://github.com/jviotti
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

'use strict';

var m = require('mochainon');
var StreamBuffers = require('stream-buffers');
var fs = require('fs');
var path = require('path');
var sliceStream = require('../');

describe('slice-stream2', function() {

  it('should slice a stream', function(done) {
    var sourceStream = new StreamBuffers.ReadableStreamBuffer();
    sourceStream.put('Hello World');

    var writableStream = new StreamBuffers.WritableStreamBuffer();

    sourceStream
      .pipe(sliceStream({ bytes: 5 }))
      .pipe(writableStream)
      .once('close', function() {
        var str = writableStream.getContentsAsString('utf8');
        m.chai.expect(str).to.equal('Hello');
        sourceStream.destroy();
        done();
      });
  });

  it('should not throw if the stream length is not divisible by the high water mark', function(done) {
    var unalignedDataPath = path.join(__dirname, 'unaligned.data');
    var sourceStream = fs.createReadStream(unalignedDataPath, { highWaterMark: 10 });
    var writableStream = new StreamBuffers.WritableStreamBuffer();
    var errorSpy = m.sinon.spy();

    sourceStream
      .pipe(sliceStream({ bytes: 1 }))
      .pipe(writableStream)
      .on('error', errorSpy)
      .once('close', function() {
        setTimeout(function() {
          m.chai.expect(errorSpy).to.not.have.been.called;
          done();
        }, 1000);
      });
  });

});
