#!/usr/bin/env node
// Copyright IBM Corp. 2016. All Rights Reserved.
// Node module: apiconnect-cli-apps
// US Government Users Restricted Rights - Use, duplication or disclosure
// restricted by GSA ADP Schedule Contract with IBM Corp.

/********************************************************* {COPYRIGHT-TOP} ***
 * IBM Confidential
 * OCO Source Materials
 * 5725-C11, 5725-C12, 7198-8FX, 5725-F70, 5725-F71, 5725-F72, 5725-L30
 *
 * (C) Copyright IBM Corporation 2015  All Rights Reserved.
 *
 * The source code for this program is not published or otherwise
 * divested of its trade secrets, irrespective of what has been
 * deposited with the U.S. Copyright Office.
 ********************************************************* {COPYRIGHT-END} **/

var ApicCliUtil = require('apiconnect-cli-util');
var ApimAppsListFormatter = require('./formatter/apps_list_formatter');

var cliConfig = require('apiconnect-cli-config');
var f = require('util').format;
var logger = require('apiconnect-cli-logger');
var path = require('path');

var api = require('../index');

var providerApps = ApicCliUtil.ProviderApps;
var providerOrgName = ApicCliUtil.Util.providerOrgName;

function appsListCmd(options) {
  var program = {};
  var fmt = new ApimAppsListFormatter();

  program.org = options.organization;
  program.allOrganizations = options.allOrganizations;
  program.server = options.server;

  if (!program.server) {
    var config = cliConfig.loadConfig();
    var appConfig = config.getOne('app') || {};
    program.server = appConfig.hostname;
  }

  if (!program.server) {
    throw new Error(f('--server is required.'));
  }
  if (program.org && program.allOrganizations) {
    throw new Error(f('Should specify only one of --organization ORGANIZATION | --all-organizations'));
  }
  if (!program.org && !program.allOrganizations) {
    var org = providerOrgName();
    if (!org) {
      throw new Error(f('--organization ORGANIZATION | --all-organizations is required'));
    }
    program.org = org;
  }

  return providerApps.listAll(program).then(function(body) {
    fmt.format(body);
  }).catch(function(err) {
    var first_err = Object.keys(err.error.errors[0]);
    fmt.error(err.error.errors[0][first_err]);
  });
};
exports.appsListCmd = appsListCmd;

function buildCmd(opts) {
  var zip = true;
  var install = !!opts.install;
  var scripts = !!opts.scripts;
  // Don't validate install / scripts as that'll be handled by build api
  if (opts.format === 'tar') {
    zip = false;
  } else if (opts.format && opts.format !== 'zip') {
    // user provided something, but it's not 'tar' or 'zip' warn
    throw new Error(f('Unexpected format provided. Found %s, expected tar or zip', opts.format));
  }
  return api.build(process.cwd(), { zip: zip, install: install, scripts: scripts }).then(function(res) {
    logger.writeln('Built', path.join('..', path.basename(res)));
    return;
  });
}
exports.buildCmd = buildCmd;
