#!/usr/bin/env node
//------------------------------------------------------------------
// SDB Management Script
//
// Copyright (c) 2014. Paul Jackson
//

//------------------------------------------------------------------
// Dependencies

var aws    = require('aws-sdk')
  , util   = require('util')
  , path   = require('path')
  , fs     = require('fs')
  , colors = require('colors');
  

//------------------------------------------------------------------
// Initialisation

aws.config.loadFromPath(__dirname + '/../config/aws-sdb-config.json');


//------------------------------------------------------------------
// Private Members

var sdb = new aws.SimpleDB()
  , command = process.argv[2]
  , param   = process.argv[3]
  , option  = process.argv[4];


//------------------------------------------------------------------
// Private Methods

function removeItem(domain, name) {
  var params = {
    DomainName: domain,
    ItemName: name
  };
  
  console.log(' > Deleting attributes...');
  sdb.deleteAttributes(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
    console.log(' > Complete');
  });
}

function uploadAttributes(domain, source) {
  console.log(' > Parsing attributes...');
  var attributes = JSON.parse(fs.readFileSync(source));
  var params = {
    Attributes: attributes,
    DomainName: domain,
    ItemName: path.basename(source, '.json')
  };

  console.log(' > Uploading attributes...', params);
  sdb.putAttributes(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
    console.log(' > Complete');
  });
}

function listObjects (name) {
  if (!name) throw new Error('Missing parameter: [name]');
    
  console.log(' > Getting domain objects...');
  var req = sdb.select({'SelectExpression': util.format('SELECT * FROM `%s` LIMIT 500', name)}, function(err, data) {
    if (err) throw new Error(err);
    data.Items.forEach(function(item) {
      console.log(util.format(' >> Item: %s'.grey, item.Name.green));
      item.Attributes.forEach(function(attrib) {
        console.log(util.format('    %s : %s'.yellow, attrib.Name.cyan, (((attrib||{}).Value)||'').grey));
      });
    });
    console.log(' > Complete');
  });
  
  req.on('error', function(r) {
    console.log(' !! Error'.red);
    console.log(r);
  });
}

function listDomains () {
  console.log(' > Getting domains...')
  var req = sdb.listDomains({}, function(err, data) {
    if (err) throw new Error(err);
    data.DomainNames.forEach(function(domain) {
      console.log(util.format(' >> Domain: %s'.grey, domain.yellow));
    });
    console.log(' > Complete');
  });
  
  req.on('error', function(r) {
    console.log(' !! Error'.red);
    console.log(r);
  });
}

function showHelp () {
  console.log('');
  console.log(' Script to help manage SimpleDB objects.');  
  console.log('');
  console.log(' --ls <domain>            : Lists the objects in a domain.');
  console.log(' --send <domain> <params> : Runs the upload request.');
  console.log(' --remove <domain> <name> : Removes the item with the name specified');
  console.log(' --list                   : Lists all the domains.');
  console.log(' --help                   : Shows this screen.');
  console.log('');
}


//------------------------------------------------------------------
// Entry Point

switch (command) {
  case '--ls':
    listObjects(param);
    break;
  case '--send':
    uploadAttributes(param, option);
    break;
  case '--remove':
    removeItem(param, option);
    break;
  case '--list':
    listDomains();
    break;
  case '--help':
  default:
    showHelp();
    break;
}