// Generated by CoffeeScript 1.10.0
(function() {
  var buffer, cfgPath, config, error, error1, ex, fs, path, sql, write;

  fs = require('fs');

  path = require('path');

  sql = require('./main');

  write = function(text) {
    return process.stdout.write(text);
  };

  Buffer.prototype.toJSON = function() {
    return "0x" + (this.toString('hex'));
  };

  cfgPath = process.argv[2];

  if (!cfgPath) {
    cfgPath = process.cwd();
  }

  cfgPath = path.resolve(cfgPath);

  if (fs.lstatSync(cfgPath).isDirectory()) {
    cfgPath = path.resolve(cfgPath, './.mssql.json');
  }

  if (!fs.existsSync(cfgPath)) {
    console.error("Config file not found.");
    process.exit(1);
  }

  try {
    config = fs.readFileSync(cfgPath);
  } catch (error) {
    ex = error;
    console.error("Failed to load config file. " + ex.message);
    process.exit(1);
  }

  try {
    config = JSON.parse(config);
  } catch (error1) {
    ex = error1;
    console.error("Failed to parse config file. " + ex.message);
    process.exit(1);
  }

  buffer = [];

  process.stdin.setEncoding('utf8');

  process.stdin.on('readable', function() {
    return buffer.push(process.stdin.read());
  });

  process.stdin.on('end', function() {
    var index, rst, statement;
    statement = buffer.join('');
    rst = 0;
    index = 0;
    if (!statement.length) {
      console.error("Statement is empty.");
      process.exit(1);
    }
    return sql.connect(config, function(err) {
      var request;
      if (err) {
        console.error(err.message);
        process.exit(1);
      }
      write('[');
      request = new sql.Request;
      request.stream = true;
      request.on('recordset', function(metadata) {
        index = 0;
        if (rst++ > 0) {
          write('],');
        }
        return write('[');
      });
      request.on('error', function(err) {
        console.error(err.message);
        sql.close();
        return process.exit(1);
      });
      request.on('row', function(row) {
        if (index++ > 0) {
          write(',');
        }
        return write(JSON.stringify(row));
      });
      request.on('done', function() {
        if (rst > 0) {
          write(']');
        }
        write(']\n');
        sql.close();
        return process.exit(0);
      });
      return request.query(statement);
    });
  });

  process.on('uncaughtException', function(err) {
    if (err.code === 'EPIPE') {
      console.error("Failed to pipe output stream.");
    } else {
      console.error(err.message);
    }
    return process.exit(1);
  });

}).call(this);
