// Generated by CoffeeScript 1.7.1
var metadataParse, parser;

metadataParse = require('../metadata-parser');

parser = function(buffer, colMetadata, options) {
  var c, colName, column, columnCount, columns, metadata, numberOfTableNameParts, part, tableName, _i;
  columnCount = buffer.readUInt16LE();
  columns = [];
  for (c = _i = 0; 0 <= columnCount ? _i < columnCount : _i > columnCount; c = 0 <= columnCount ? ++_i : --_i) {
    metadata = metadataParse(buffer, options);
    if (metadata.type.hasTableName) {
      if (options.tdsVersion >= '7_2') {
        numberOfTableNameParts = buffer.readUInt8();
        tableName = (function() {
          var _j, _results;
          _results = [];
          for (part = _j = 1; 1 <= numberOfTableNameParts ? _j <= numberOfTableNameParts : _j >= numberOfTableNameParts; part = 1 <= numberOfTableNameParts ? ++_j : --_j) {
            _results.push(buffer.readUsVarchar('ucs2'));
          }
          return _results;
        })();
      } else {
        tableName = buffer.readUsVarchar('ucs2');
      }
    } else {
      tableName = void 0;
    }
    colName = buffer.readBVarchar();
    if (options.columnNameReplacer) {
      colName = options.columnNameReplacer(colName, c, metadata);
    } else if (options.camelCaseColumns) {
      colName = colName.replace(/^[A-Z]/, function(s) {
        return s.toLowerCase();
      });
    }
    column = {
      userType: metadata.userType,
      flags: metadata.flags,
      type: metadata.type,
      colName: colName,
      collation: metadata.collation,
      precision: metadata.precision,
      scale: metadata.scale,
      udtInfo: metadata.udtInfo,
      dataLength: metadata.dataLength,
      tableName: tableName
    };
    columns.push(column);
  }
  return {
    name: 'COLMETADATA',
    event: 'columnMetadata',
    columns: columns
  };
};

module.exports = parser;
