var Stream    = require('stream').Stream;
var util      = require('util');
var net       = require('net');
var constants = require('../constants');

module.exports = TcpVideoStream;
util.inherits(TcpVideoStream, Stream);
function TcpVideoStream(options) {
  Stream.call(this);

  options = options || {};

  this.readable   = true;
  this._socket    = options.socket || new net.Socket();
  this._port      = options.port || constants.ports.VIDEO;
  this._ip        = options.ip || constants.DEFAULT_DRONE_IP;
  this._timeout   = options.timeout || 1 * 1000;
  this._expectFIN = false;
}

TcpVideoStream.prototype.connect = function(cb) {
  cb = cb || function() {};

  this._socket.removeAllListeners();                // To avoid duplicates when re-connecting
  this._socket.connect(this._port, this._ip);
  this._socket.setTimeout(this._timeout);

  var self = this;
  this._socket
    .on('connect', function() {
      self._socket.removeListener('error', cb);
      self._socket.on('error', function(err) {
        self.emit('error', err);
      });
      cb(null);
    })
    .on('data', function(buffer) {
      self.emit('data', buffer);
    })
    .on('timeout', function() {
      var err = new Error('TcpVideoStream timeout after ' + self._timeout + ' ms.');
      self.emit('error', err);
      self.emit('close', err);
      self._socket.destroy();
    })
    .on('error', cb)
    .on('end', function() {
      if (self._expectFIN) {
        self.emit('close');
        return;
      }

      var err = new Error('TcpVideoStream received FIN unexpectedly.');
      self.emit('error', err);
      self.emit('close', err);
    });

};

TcpVideoStream.prototype.end = function() {
  this._expectFIN = true;
  this._socket.end();
};
