'use strict';

// TODO: rename getDataUrl to vl.data.getUrl() ?

var util = require('./util');

var vldata = module.exports = {},
  vlfield = require('./field');

vldata.getUrl = function getDataUrl(encoding, stats) {
  if (!encoding.config('useVegaServer')) {
    // don't use vega server
    return encoding.config('dataUrl');
  }

  if (encoding.length() === 0) {
    // no fields
    return;
  }

  var fields = [];
  encoding.forEach(function(field, encType) {
    var obj = {
      name: encoding.field(encType, true),
      field: field.name
    };
    if (field.aggr) {
      obj.aggr = field.aggr;
    }
    if (field.bin) {
      obj.binSize = util.getbins(stats[field.name], encoding.bin(encType).maxbins).step;
    }
    fields.push(obj);
  });

  var query = {
    table: encoding.config('vegaServerTable'),
    fields: fields
  };

  return encoding.config('vegaServerUrl') + '/query/?q=' + JSON.stringify(query);
};

/**
 * @param  {Object} data data in JSON/javascript object format
 * @return Array of {name: __name__, type: "number|text|time|location"}
 */
vldata.getSchema = function(data, order) {
  var schema = [],
    fields = util.keys(data[0]);

  fields.forEach(function(k) {
    // find non-null data
    var i = 0, datum = data[i][k];
    while (datum === '' || datum === null || datum === undefined) {
      datum = data[++i][k];
    }

    datum = util.parse(datum);
    var type = (typeof datum === 'number') ? 'Q':
      (datum instanceof Date) ? 'T' : 'O';

    schema.push({name: k, type: type});
  });

  schema = util.stablesort(schema, order || vlfield.order.typeThenName, vlfield.order.name);

  return schema;
};

vldata.getStats = function(data) { // hack
  var stats = {},
    fields = util.keys(data[0]);

  fields.forEach(function(k) {
    var column = data.map(function(d) {return d[k];});

    // Hack
    var val = util.parse(data[0][k]);
    var type = (typeof val === 'number') ? 'Q':
      (val instanceof Date) ? 'T' : 'O';

    var stat = {};
    if (typeof val === 'number') {
      stat = util.minmax(util.numbers(column));
    } else if (val instanceof Date) {
      stat = util.minmax(util.dates(column));
    } else {
      stat = util.minmax(column);
    }

    console.log(column, stat);

    stat.cardinality = util.uniq(data, k);
    stat.count = data.length;

    stat.maxlength = data.reduce(function(max,row) {
      if (row[k] === null) {
        return max;
      }
      var len = row[k].toString().length;
      return len > max ? len : max;
    }, 0);

    stat.numNulls = data.reduce(function(count, row) {
      return row[k] === null ? count + 1 : count;
    }, 0);

    var numbers = util.numbers(column);

    if (numbers.length > 0) {
      stat.skew = util.skew(numbers);
      stat.stdev = util.stdev(numbers);
      stat.mean = util.mean(numbers);
      stat.median = util.median(numbers);
    }

    var sample = {};
    while(Object.keys(sample).length < Math.min(stat.cardinality, 10)) {
      var value = data[Math.floor(Math.random() * data.length)][k];
      sample[value] = true;
    }
    stat.sample = Object.keys(sample);

    stats[k] = stat;
  });
  stats.count = data.length;
  return stats;
};

@@ -2212,40 +2212,8 @@
  %7D%0A%0A
-    console.log(column, stat);%0A%0A
     

remove log