#!/usr/bin/env node
const program = require('commander');
const chalk = require('chalk');
const cloudformation = require('./cloudformation');

const log = console.log;

const tools = require('./tools');
const meta = require('../package.json');

let stackFilter;

program
  .version(meta.version)
  .arguments('<stack>')
  .option('-l, --long', 'Shows all resource data')
  .action(function (filter) {
    stackFilter = filter;
  })

program.parse(process.argv);

let args = program.parse(process.argv).args;
if (args.length === 0 && tools.inProjectDir()) {
  console.log('stack name must be provided')
  process.exit(0);
}

const ROW_TYPE_LEN = 40;
const ROW_STATUS_LEN = 21;

function printProperty(resource, property) {
  const indent = tools.fixed(' ', ROW_TYPE_LEN).substring(5);
  const field = tools.fixed(property, ROW_STATUS_LEN);
  if (resource[property]) {
    console.log(indent + field + resource[property]);
  }
}

function printResourceRow(resource) {
  const rowType = tools.fixed(resource.ResourceType, ROW_TYPE_LEN).substring(5);
  const status = tools.fixed(resource.ResourceStatus, ROW_STATUS_LEN);
  console.log(rowType + status + chalk.blue(resource.LogicalResourceId));
  if (program.long) {
    ['PhysicalResourceId',
      'LastUpdatedTimestamp',
      'ResourceStatusReason'].map(p => printProperty(resource, p));
  }
  return resource;
}

function listResources(stackId) {
  return cloudformation.listResources(stackId)
    .then(resources => {
      resources.map(resource => printResourceRow(resource));
    })
    .catch(err => tools.handleError(err));
}

tools.inProjectDir() ? listResources(args[0]) : listResources(tools.stackId() || tools.stackName());