// Generated by CoffeeScript 1.7.1
var OPTION, RpcRequestPayload, STATUS, WritableTrackingBuffer, typeByName, writeAllHeaders;

WritableTrackingBuffer = require('./tracking-buffer/tracking-buffer').WritableTrackingBuffer;

writeAllHeaders = require('./all-headers').writeToTrackingBuffer;

typeByName = require('./data-type').typeByName;

OPTION = {
  WITH_RECOMPILE: 0x01,
  NO_METADATA: 0x02,
  REUSE_METADATA: 0x04
};

STATUS = {
  BY_REF_VALUE: 0x01,
  DEFAULT_VALUE: 0x02
};


/*
  s2.2.6.5
 */

RpcRequestPayload = (function() {
  function RpcRequestPayload(request, txnDescriptor, options) {
    var buffer, optionFlags, outstandingRequestCount, param, parameter, statusFlags, _base, _base1, _base2, _i, _len, _ref, _ref1, _ref2, _ref3;
    this.request = request;
    buffer = new WritableTrackingBuffer(500);
    this.procedure = this.request.sqlTextOrProcedure;
    if (options.tdsVersion >= '7_2') {
      outstandingRequestCount = 1;
      writeAllHeaders(buffer, txnDescriptor, outstandingRequestCount);
    }
    if (typeof this.procedure === 'string') {
      buffer.writeUsVarchar(this.procedure);
    } else {
      buffer.writeUShort(0xFFFF);
      buffer.writeUShort(this.procedure);
    }
    optionFlags = 0;
    buffer.writeUInt16LE(optionFlags);
    _ref = this.request.parameters;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      parameter = _ref[_i];
      statusFlags = 0;
      if (parameter.output) {
        statusFlags |= STATUS.BY_REF_VALUE;
      }
      buffer.writeBVarchar('@' + parameter.name);
      buffer.writeUInt8(statusFlags);
      param = {
        value: parameter.value
      };
      if ((parameter.type.id & 0x30) === 0x20) {
        param.length = (_ref1 = parameter.length) != null ? _ref1 : typeof (_base = parameter.type).resolveLength === "function" ? _base.resolveLength(parameter) : void 0;
      }
      if (parameter.type.hasPrecision) {
        param.precision = (_ref2 = parameter.precision) != null ? _ref2 : typeof (_base1 = parameter.type).resolvePrecision === "function" ? _base1.resolvePrecision(parameter) : void 0;
      }
      if (parameter.type.hasScale) {
        param.scale = (_ref3 = parameter.scale) != null ? _ref3 : typeof (_base2 = parameter.type).resolveScale === "function" ? _base2.resolveScale(parameter) : void 0;
      }
      parameter.type.writeTypeInfo(buffer, param, options);
      parameter.type.writeParameterData(buffer, param, options);
    }
    this.data = buffer.data;
  }

  RpcRequestPayload.prototype.toString = function(indent) {
    indent || (indent = '');
    return indent + ("RPC Request - " + this.procedure);
  };

  return RpcRequestPayload;

})();

module.exports = RpcRequestPayload;
