#!/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('The --server option is required.');
  }
  if (!program.org && !program.allOrganizations) {
    var org = providerOrgName();
    if (!org) {
      throw new Error('The --organization option 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('The --format %s is not supported.', 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;

function appsSet(options) {
  return ApicCliUtil.RemoteApps.resolve(options).then(function(impl) {
    if (options.status === 'online') {
      return impl.servicesStart(options);
    } else if (options.status === 'offline') {
      return impl.servicesStop(options);
    }
  }).then(function(res) {
    options.logger.writeln(
      'Updated apic-app://%s/orgs/%s/apps/%s (status: %s)',
      options.server, options.organization, options.app, options.status
    );
  }).catch(function(err) {
    options.logger.debug(err);
    options.logger.debug(err.stack);
    throw new Error(f(
      'Failed to update apic-app://%s/orgs/%s/apps/%s',
      options.server, options.organization, options.app
    ));
  });
}
exports.appsSet = appsSet;

function appsGet(options) {
  return ApicCliUtil.RemoteApps.resolve(options).then(function(impl) {
    return impl.serviceStatus(options).then(function(status) {
      options.logger.writeln('name: %s', options.app);
      options.logger.writeln('title: %s', options.providerApp.title);
      options.logger.writeln(
        'url: apic-app://%s/orgs/%s/apps/%s',
        options.server, options.organization, options.app
      );
      options.logger.writeln('status: %s', status);
      options.logger.writeln('organization: %s', options.organization);
    });
  });
}
exports.appsGet = appsGet;

