'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TcpOutbound = exports.TcpInbound = undefined;

var _net = require('net');

var _net2 = _interopRequireDefault(_net);

var _defs = require('./defs');

var _utils = require('../utils');

var _constants = require('../constants');

var _acl = require('../core/acl');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

class TcpInbound extends _defs.Inbound {

  constructor(props) {
    super(props);
    this._socket = null;
    this._destroyed = false;
    this.onError = this.onError.bind(this);
    this.onReceive = this.onReceive.bind(this);
    this.onDrain = this.onDrain.bind(this);
    this.onTimeout = this.onTimeout.bind(this);
    this.onHalfClose = this.onHalfClose.bind(this);
    this.onClose = this.onClose.bind(this);
    this._socket = this._conn;
    this._socket.on('error', this.onError);
    this._socket.on('data', this.onReceive);
    this._socket.on('drain', this.onDrain);
    this._socket.on('timeout', this.onTimeout);
    this._socket.on('end', this.onHalfClose);
    this._socket.on('close', this.onClose);
    this._socket.setTimeout && this._socket.setTimeout(this._config.timeout);
  }

  get name() {
    return 'tcp:inbound';
  }

  get bufferSize() {
    return this._socket ? this._socket.bufferSize : 0;
  }

  get writable() {
    return this._socket && !this._socket.destroyed && this._socket.writable;
  }

  write(buffer) {
    if (this.writable) {
      this._socket.write(buffer);
    }
  }

  onError(err) {
    _utils.logger.warn(`[${this.name}] [${this.remote}] ${err.message}`);
    this.emit('_error', err);
  }

  onReceive(buffer) {
    this.emit('data', buffer);

    const outbound = this.getOutbound();
    if (outbound && outbound.bufferSize >= _constants.MAX_BUFFERED_SIZE) {
      _utils.logger.debug(`[${this.name}] [${this.remote}] recv paused due to outbound.bufferSize=${outbound.bufferSize} >= ${_constants.MAX_BUFFERED_SIZE}`);
      this.pause();
      outbound.once('drain', () => {
        if (this._socket && !this._socket.destroyed) {
          _utils.logger.debug(`[${this.name}] [${this.remote}] resume to recv`);
          this.resume();
        }
      });
    }
  }

  onDrain() {
    this.emit('drain');
  }

  onTimeout() {
    _utils.logger.warn(`[${this.name}] [${this.remote}] timeout: no I/O on the connection for ${this._config.timeout / 1e3}s`);
    this.onClose();
  }

  onHalfClose() {
    const outbound = this.getOutbound();
    outbound && outbound.end && outbound.end();
  }

  onClose() {
    this.close();
    const outbound = this.getOutbound();
    if (outbound) {
      outbound.close();
      this.setOutbound(null);
    }
  }

  pause() {
    if (this._socket && typeof this._socket.pause === 'function') {
      this._socket.pause();
    }
  }

  resume() {
    if (this._socket && typeof this._socket.resume === 'function') {
      this._socket.resume();
    }
  }

  end() {
    this._socket && this._socket.end();
  }

  close() {
    const doClose = () => {
      if (this._socket) {
        this._socket.destroy();
        this._socket = null;
      }
      if (!this._destroyed) {
        this._destroyed = true;
        this.emit('close');
      }
    };
    if (this.bufferSize > 0) {
      this.once('drain', doClose);
    } else {
      doClose();
    }
  }

  onBroadcast(action) {
    switch (action.type) {
      case _acl.ACL_PAUSE_RECV:
        this.pause();
        break;
      case _acl.ACL_RESUME_RECV:
        this.resume();
        break;
      default:
        break;
    }
  }

}

exports.TcpInbound = TcpInbound;
class TcpOutbound extends _defs.Outbound {

  constructor(props) {
    super(props);
    this._socket = null;
    this._destroyed = false;
    this.onError = this.onError.bind(this);
    this.onReceive = this.onReceive.bind(this);
    this.onDrain = this.onDrain.bind(this);
    this.onTimeout = this.onTimeout.bind(this);
    this.onHalfClose = this.onHalfClose.bind(this);
    this.onClose = this.onClose.bind(this);
  }

  get name() {
    return 'tcp:outbound';
  }

  get bufferSize() {
    return this._socket ? this._socket.bufferSize : 0;
  }

  get writable() {
    return this._socket && !this._socket.destroyed && this._socket.writable;
  }

  write(buffer) {
    if (this.writable) {
      this._socket.write(buffer);
    }
  }

  onError(err) {
    _utils.logger.warn(`[${this.name}] [${this.remote}] ${err.message}`);
    this.emit('_error', err);
  }

  onReceive(buffer) {
    this.emit('data', buffer);

    const inbound = this.getInbound();
    if (inbound && inbound.bufferSize >= _constants.MAX_BUFFERED_SIZE) {
      _utils.logger.debug(`[${this.name}] [${this.remote}] recv paused due to inbound.bufferSize=${inbound.bufferSize} >= ${_constants.MAX_BUFFERED_SIZE}`);
      this.pause();
      inbound.once('drain', () => {
        if (this._socket && !this._socket.destroyed) {
          _utils.logger.debug(`[${this.name}] [${this.remote}]  resume to recv`);
          this.resume();
        }
      });
    }
  }

  onDrain() {
    this.emit('drain');
  }

  onTimeout() {
    _utils.logger.warn(`[${this.name}] [${this.remote}] timeout: no I/O on the connection for ${this._config.timeout / 1e3}s`);
    this.onClose();
  }

  onHalfClose() {
    const inbound = this.getInbound();
    inbound && inbound.end && inbound.end();
  }

  onClose() {
    this.close();
    const inbound = this.getInbound();
    if (inbound) {
      inbound.close();
      this.setInbound(null);
    }
  }

  pause() {
    if (this._socket && typeof this._socket.pause === 'function') {
      this._socket.pause();
    }
  }

  resume() {
    if (this._socket && typeof this._socket.resume === 'function') {
      this._socket.resume();
    }
  }

  end() {
    this._socket && this._socket.end();
  }

  close() {
    const doClose = () => {
      if (this._socket) {
        this._socket.destroy();
        this._socket = null;
      }
      if (!this._destroyed) {
        this._destroyed = true;
        this.emit('close');
      }
    };
    if (this.bufferSize > 0) {
      this.once('drain', doClose);
    } else {
      doClose();
    }
  }

  onBroadcast(action) {
    switch (action.type) {
      case _acl.ACL_PAUSE_SEND:
        this.pause();
        break;
      case _acl.ACL_RESUME_SEND:
        this.resume();
        break;
      default:
        break;
    }
  }

  async connect(host, port, force = false) {
    return new Promise(async resolve => {
      if (!this._socket || force) {
        let targetHost, targetPort;
        try {
          const { is_server, server_host, server_port, server_pathname } = this._config;
          if (is_server) {
            targetHost = host;
            targetPort = port;
          } else {
            targetHost = server_host;
            targetPort = server_port;
          }

          if (this._socket && !this._socket.destroyed) {
            this._socket.destroy();
            this._socket.removeAllListeners();
          }
          this._socket = await this._connect({ host: targetHost, port: targetPort, pathname: server_pathname });
          this._socket.on('connect', resolve);
          this._socket.on('error', this.onError);
          this._socket.on('end', this.onHalfClose);
          this._socket.on('close', this.onClose);
          this._socket.on('timeout', this.onTimeout);
          this._socket.on('data', this.onReceive);
          this._socket.on('drain', this.onDrain);
          this._socket.setTimeout(this._config.timeout);
        } catch (err) {
          _utils.logger.error(`[${this.name}] [${this.remote}] cannot connect to ${targetHost}:${targetPort}, ${err.message}`);
          this.emit('_error', err);
          this.onClose();
        }
      } else {
        resolve();
      }
    });
  }

  async _connect({ host, port }) {
    const ip = await _utils.DNSCache.get(host);
    _utils.logger.info(`[${this.name}] [${this.remote}] connecting to tcp://${host}:${port}` + (_net2.default.isIP(host) ? '' : ` resolved=${ip}`));
    return _net2.default.connect({ host: ip, port });
  }

}
exports.TcpOutbound = TcpOutbound;