#!/usr/bin/env node

var path = require('path');
var redis = require('redis');
var Step = require('step');


function usage(me, exitcode) {
  console.log("Usage: " + me + " [--env <environment>] <username> [<tablename>|~<token>]");
  process.exit(exitcode);
}

var node_path = process.argv.shift(); 
var script_path = process.argv.shift(); 
var basedir = path.dirname(script_path);
var me = path.basename(script_path);

var ENV = 'development.js';
var username, token;
var arg;
while ( arg = process.argv.shift() ) {
  if ( arg == '--env' ) {
    ENV = process.argv.shift();
  }
  else if ( ! username ) {
    username = arg;
  }
  else if ( ! token ) {
    token = arg;
  }
  else {
    console.warn("Unused parameter " + arg);
  }
}

if ( ! username ) usage(me, 1);

console.log("Using environment " + ENV);

global.environment = require('../config/environments/' + ENV);
// _after_ setting global.environment
var serverOptions = require('../lib/cartodb/server_options')();

var client;
var dbname;
Step(
  function getClient() {
    client = redis.createClient(serverOptions.redis.port, serverOptions.redis.host);
    client.on('connect', this);
  },
  function getUserMeta(err) {
    if ( err ) throw err;
    client.select(5);
    client.hgetall('rails:users:' + username, this);
  },
  function readDB(err, data) {
    if ( err ) throw err;
    if ( ! data )
      throw new Error('Username ' + username + ' unknown by redis on port '
        + serverOptions.redis.port + ' (try CARTODB/script/restore_redis?)');
    //console.log("Data:"); console.dir(data);
    dbname = data['database_name'];
    console.log("Database name for user " + username + ": " + dbname);
    client.select(0);
    return null;
  },
  function showTokens(err) {
    if ( err ) throw err;
    if ( token ) return null;
    var next = this;
    Step(
      function getTokens() {
        client.keys('map_style|' + dbname + '|*', this);
      },
      function showTokens(err, data) {
        if (err) throw err;
        if ( data ) console.log(data.join('\n'));
        return null;
      },
      function showTokensFinish(err) {
        next(err);
      }
    );
  },
  function showStyle(err) {
    if ( err ) throw err;
    if ( ! token ) return null;
    var next = this;
    Step(
      function getStyle() {
        client.get('map_style|' + dbname + '|' + token, this);
      },
      function showStyle(err, data) {
        if ( err ) throw err;
        if ( ! data ) {
          throw new Error(token + ': no such map style known by redis on port '
            + serverOptions.redis.port);
        }
//console.log("data: " + data);
        var x=JSON.parse(data);
        printMapnikStyle(x, this);
      },
      function showStyleFinish(err) {
        next(err);
      }
    );
  },
  function finish(err) {
    if ( err ) {
      console.error(err.message)
      process.exit(1);
    }
    process.exit(0);
  }
);

function printMapnikStyle(x, callback) {
  console.log('style: ' + x.style);
  console.log('version: ' + x.version);
  var grainstore = require(basedir + '/../node_modules/windshaft/node_modules/grainstore/lib/grainstore');
  var mml_store = new grainstore.MMLStore(serverOptions.redis, serverOptions.grainstore);
  var builderconfig = {dbname:dbname};
  if ( token.match(/^~/) ) {
    builderconfig.token = token.substring(1);
  } else {
    builderconfig.table = token;
  }
  var mml_builder;
  Step(
    function getBuilder() {
      mml_builder = mml_store.mml_builder(builderconfig, this);
    },
    function getXML(err, builder) {
      if ( err ) throw err;
      mml_builder.toXML(this);
    },
    function showXML(err, xml) {
      if ( err ) throw err;
      console.log('- XML - ');
      console.log(xml);
      return null;
    },
    function finish(err) {
      callback(err);
    }
  );
}

