/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ "use strict"; var __rt=require('streamline/lib/callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb,__catch=__rt.__catch,__tryCatch=__rt.__tryCatch; var util = require("util");

















var profile = require("../../../util/profile");
var utils = require("../../../util/utils");
var moment = require("moment");
var $ = utils.getLocaleString;

exports.getADGraphClient = function getADGraphClient(subscription) {
  return utils.createGraphManagementClient(subscription);};


exports.createApplication = function exports_createApplication__1(cli, name, homePage, identifierUris, options, _) { var startDate, endDate, keyType, keyUsage, uris, appParams, subscription, client, application, withProgress, currentUserObject; var __frame = { name: "exports_createApplication__1", line: 28 }; return __func(_, this, arguments, exports_createApplication__1, 5, __frame, function __$exports_createApplication__1() {
    if (!name) {
      return _(null, cli.missingArgument("name")); } ;


    if (!homePage) {
      return _(null, cli.missingArgument("home-page")); } ;


    if (!identifierUris) {
      return _(null, cli.missingArgument("identifier-uris")); } ;


    if ((options.password && options.keyValue)) {
      return _(new Error($("specify either --password or --key-value, but not both."))); } ;


    startDate = (options.startDate ? new Date(Date.parse(options.startDate)) : new Date(Date.now()));










    return (function ___closure(_) { var date, m; if (options.endDate) { return _(null, new Date(Date.parse(options.endDate))); } else { date = new Date(startDate); m = moment(date); m.add(1, "years"); date = new Date(m.toISOString()); return _(null, date); } ; _(); })(__cb(_, __frame, 18, 16, function ___(__0, __2) { endDate = __2;

      keyType = (options.keyType ? options.keyType : "AsymmetricX509Cert");
      keyUsage = (options.keyUsage ? options.keyUsage : "Verify");

      uris = (identifierUris ? identifierUris.split(",") : []);

      appParams = {
        availableToOtherTenants: (options.available ? true : false),
        displayName: name,
        homepage: homePage,
        identifierUris: uris };


      if (options.replyUrls) {
        appParams.replyUrls = options.replyUrls.split(","); } ;


      if (options.password) {
        appParams.passwordCredentials = [{
          startDate: startDate,
          endDate: endDate,
          keyId: utils.uuidGen(),
          value: options.password },]; } else {

        if (options.keyValue) {
          appParams.keyCredentials = [{
            startDate: startDate,
            endDate: endDate,
            keyId: utils.uuidGen(),
            value: options.keyValue,
            usage: keyUsage,
            type: keyType },]; } ; } ;



      subscription = profile.current.getSubscription(options.subscription);
      client = exports.getADGraphClient(subscription);

      application = null;
      withProgress = cli.interaction.withProgress.bind(cli.interaction); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$exports_createApplication__1() {

            return withProgress(util.format($("Creating application %s"), name), function __1(log, _) { var __frame = { name: "__1", line: 99 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {

                return client.applications.create(appParams, __cb(_, __frame, 1, 33, _, true)); }); }, __cb(_, __frame, 70, 18, function ___(__0, __4) { application = __4;

              return _(null, application); }, true)); }); })(function ___(ex, __result) { __catch(function __$exports_createApplication__1() { if (ex) { return (function __$exports_createApplication__1(__then) {

                if ((ex.statusCode && (ex.statusCode === 403))) {

                  return client.objects.getCurrentUser(__cb(_, __frame, 78, 45, function ___(__0, __3) { currentUserObject = __3;
                    if (((currentUserObject && currentUserObject.userType) && (currentUserObject.userType === "Guest"))) {
                      return _(new Error($("Creating an application is not allowed for a Guest user. Please contact your administrator to be added as a member in your tenant."))); } ; __then(); }, true)); } else { __then(); } ; })(function __$exports_createApplication__1() {


                return _(ex); }); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$exports_createApplication__1() { _(); }); }); }, true)); });};



exports.getObjectId = function exports_getObjectId__2(principal, graphClient, throwIfNoOption, shouldRetrieveObjectType, objectType, _) { var objects, parameters, users, servicePrincipals; var __frame = { name: "exports_getObjectId__2", line: 115 }; return __func(_, this, arguments, exports_getObjectId__2, 5, __frame, function __$exports_getObjectId__2() { return (function __$exports_getObjectId__2(__then) {
      if (principal.objectId) { return (function __$exports_getObjectId__2(__then) {

          if (shouldRetrieveObjectType) {
            return exports.getObjectsByObjectIds(graphClient, new Array(principal.objectId), true, __cb(_, __frame, 4, 28, function ___(__0, __1) { objects = __1;
              if ((objects && (objects.length > 0))) {
                objectType.value = objects[0].objectType; } ; __then(); }, true)); } else { __then(); } ; })(function __$exports_getObjectId__2() {



          return _(null, principal.objectId); }); } else { __then(); } ; })(function __$exports_getObjectId__2() {


      parameters = null; return (function __$exports_getObjectId__2(__then) {
        if (principal.signInName) {
          parameters = { filter: (("userPrincipalName eq '" + principal.signInName) + "'") };
          return graphClient.users.list(parameters, __cb(_, __frame, 16, 34, function ___(__0, __2) { users = __2;
            if ((users.length > 0)) {
              objectType.value = "user";
              return _(null, users[0].objectId); }
             else {
              return _(new Error($("Invalid user signInName"))); } ; __then(); }, true)); } else { __then(); } ; })(function __$exports_getObjectId__2() { return (function __$exports_getObjectId__2(__then) {



          if (principal.spn) {
            parameters = { filter: (("servicePrincipalNames/any(c:c eq '" + principal.spn) + "')") };
            return graphClient.servicePrincipals.list(parameters, __cb(_, __frame, 27, 58, function ___(__0, __3) { servicePrincipals = __3;

              if ((servicePrincipals.length > 0)) {
                objectType.value = "servicePrincipal";
                return _(null, servicePrincipals[0].objectId); }
               else {
                return _(new Error($("Invalid service principal name"))); } ; __then(); }, true)); } else { __then(); } ; })(function __$exports_getObjectId__2() {


          if (throwIfNoOption) {
            return _(new Error($("Failed to retrieve Active Dirctory Object Id"))); }
           else {
            objectType.value = "";
            return _(null, ""); } ; _(); }); }); }); });};



exports.getObjectsByObjectIds = function exports_getObjectsByObjectIds__3(graphClient, objectIds, throwOnError, _) { var objects; var __frame = { name: "exports_getObjectsByObjectIds__3", line: 159 }; return __func(_, this, arguments, exports_getObjectsByObjectIds__3, 3, __frame, function __$exports_getObjectsByObjectIds__3() {
    objects = [];
    if (((!objectIds || !objectIds.length) || (objectIds.length === 0))) {
      return _(null, objects); } ; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$exports_getObjectsByObjectIds__3() {



          return graphClient.objects.getObjectsByObjectIds({ objectIds: objectIds, includeDirectoryObjectReferences: true }, __cb(_, __frame, 7, 34, function ___(__0, __1) { objects = __1; __then(); }, true)); }); })(function ___(ex, __result) { __catch(function __$exports_getObjectsByObjectIds__3() { if (ex) {

            if ((throwOnError === true)) {
              return _(ex); } ; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$exports_getObjectsByObjectIds__3() {



        return _(null, objects); }); }); });};


exports.validateParameters = function(parameters, throwOnNoValues) {
  throwOnNoValues = (((typeof throwOnNoValues !== "undefined") ? throwOnNoValues : true));
  var parameterNames = Object.keys(parameters);


  if ((parameterNames.length === 0)) {
    return; } ;


  var values = parameterNames.filter(function(p) {
    return (!!parameters[p]); });


  if (((values.length === 0) && throwOnNoValues)) {
    throw new Error(util.format(("Please provide a value to one of the parameters '%s'"), parameterNames.join())); } ;


  if ((values.length > 1)) {
    throw new Error(util.format($("You can only specify value to one of '%s'"), values.join())); } ;};



exports.listGraphObjects = function exports_listGraphObjects__4(client, objectType, interaction, log, _) { var operationsSuffix, response, nextLink, response2;
  function displayObjects(objects) {
    if ((objects.length === 0)) {
      return; } ;

    if (utils.ignoreCaseEquals(objectType, "user")) {
      exports.displayUsers(objects, interaction, log); }
     else if (utils.ignoreCaseEquals(objectType, "group")) {
      exports.displayGroups(objects, interaction, log); }
     else if (utils.ignoreCaseEquals(objectType, "servicePrincipal")) {
      exports.displayServicePrincipals(objects, interaction, log); }   ; }; var __frame = { name: "exports_listGraphObjects__4", line: 198 }; return __func(_, this, arguments, exports_listGraphObjects__4, 4, __frame, function __$exports_listGraphObjects__4() {



    operationsSuffix = "s";
    return client[(objectType + operationsSuffix)].list(null, __cb(_, __frame, 15, 55, function ___(__0, __1) { response = __1;
      nextLink = response.odatanextLink; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$exports_listGraphObjects__4() { __more = false;
          var __4 = nextLink; if (__4) {
            return client[(objectType + operationsSuffix)].listNext(nextLink, __cb(_, __frame, 18, 58, function ___(__0, __2) { response2 = __2;

              response.push.apply(response, response2);
              nextLink = response2.odatanextLink; while (__more) { __loop(); }; __more = true; }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$exports_listGraphObjects__4() {


        displayObjects(response); _(); }); }, true)); });};


exports.listGroupMembers = function exports_listGroupMembers__5(client, groupId, interaction, log, _) { var groupMembers, nextLink, groupMembers2; var __frame = { name: "exports_listGroupMembers__5", line: 225 }; return __func(_, this, arguments, exports_listGroupMembers__5, 4, __frame, function __$exports_listGroupMembers__5() {
    return client.groups.getGroupMembers(groupId, __cb(_, __frame, 1, 35, function ___(__0, __1) { groupMembers = __1;
      nextLink = groupMembers.odatanextLink; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$exports_listGroupMembers__5() { __more = false;

          var __4 = nextLink; if (__4) {
            return client.groups.getGroupMembersNext(nextLink, __cb(_, __frame, 5, 38, function ___(__0, __2) { groupMembers2 = __2;

              groupMembers.push.apply(groupMembers, groupMembers2);
              nextLink = groupMembers2.odatanextLink; while (__more) { __loop(); }; __more = true; }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$exports_listGroupMembers__5() {


        exports.displayGroupMembers(groupMembers, interaction, log); _(); }); }, true)); });};


exports.displayApplications = function(applications, interaction, log) {
  interaction.formatOutput(applications, function(data) {
    for (var i = 0; (i < data.length); i++) {
      exports.displayAApplication(data[i], log);
      log.data(""); }; });};




exports.displayUsers = function(users, interaction, log) {
  interaction.formatOutput(users, function(data) {
    for (var i = 0; (i < data.length); i++) {
      exports.displayAUser(data[i], log);
      log.data(""); }; });};




exports.displayGroups = function(groups, interaction, log) {
  interaction.formatOutput(groups, function(data) {
    for (var i = 0; (i < data.length); i++) {
      exports.displayAGroup(data[i], log);
      log.data(""); }; });};




exports.displayServicePrincipals = function(servicePrincipals, interaction, log) {
  interaction.formatOutput(servicePrincipals, function(data) {
    for (var i = 0; (i < data.length); i++) {
      exports.displayAServicePrincipal(data[i], log);
      log.data(""); }; });};




exports.displayAServicePrincipal = function(servicePrincipal, log, showType) {
  log.data($("Object Id:              "), servicePrincipal.objectId);
  log.data($("Display Name:           "), servicePrincipal.displayName);
  log.data($("Service Principal Names:"));
  servicePrincipal.servicePrincipalNames.forEach(function(name) {
    log.data($("                        "), name); });

  if (showType) {
    log.data($("Object Type:          "), "ServicePrincipal"); } ;};



exports.displayAUser = function(user, log, showType) {
  log.data($("Object Id:      "), user.objectId);
  log.data($("Principal Name: "), user.userPrincipalName);
  log.data($("Display Name:   "), user.displayName);
  if ((user.mail || user.signInName)) {
    log.data($("E-Mail:         "), (user.mail || user.signInName)); } ;

  if (user.mailNickname) {
    log.data($("Mail Nickname:  "), user.mailNickname); } ;

  if (showType) {
    log.data($("Object Type:    "), "User"); } ;};



exports.displayAApplication = function(application, log) {
  log.data($("AppId:                  "), application.appId);
  log.data($("ObjectId:               "), application.objectId);
  log.data($("DisplayName:            "), application.displayName);
  log.data($("IdentifierUris:         "), application.identifierUris);
  log.data($("ReplyUrls:              "), application.replyUrls);
  log.data($("AvailableToOtherTenants:"), (application.availableToOtherTenants ? "True" : "False"));
  if (application.homepage) {
    log.data($("HomePage:               "), application.homepage); } ;

  if (application.appPermissions) {
    log.data($("AppPermissions:       "));
    Object.keys(application.appPermissions).forEach(function(item) {
      if (application.appPermissions[item]) {
        Object.keys(application.appPermissions[item]).forEach(function(subItem) {
          log.data($((("                         " + subItem) + ": ")), application.appPermissions[item][subItem]); }); } ; }); } ;};






exports.displayGroupMembers = function(members, interaction, log) {
  interaction.formatOutput(members, function(data) {
    for (var i = 0; (i < data.length); i++) {
      if ((data[i].objectType === "User")) {
        exports.displayAUser(data[i], log, true); }
       else if ((data[i].objectType === "Group")) {
        exports.displayAGroup(data[i], log, true); }
       else {
        log.warn(("an unexpected object type:" + data[i].objectType)); }  ;

      log.data(""); }; });};




exports.displayAGroup = function(group, log, showType) {
  log.data($("Display Name:     "), group.displayName);
  log.data($("ObjectId:         "), group.objectId);
  log.data($("Security Enabled: "), group.securityEnabled);
  log.data($("Mail Enabled:     "), (group.mailEnabled || "false"));
  if (showType) {
    log.data($("Object Type:      "), "Group"); } ;};
