/*** 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; var __ = require("underscore");

















var fs = require("fs");
var path = require("path");
var request = require("request");
var through = require("through");
var util = require("util");

var validation = require("../../../util/validation");
var profile = require("../../../util/profile");
var utils = require("../../../util/utils");
var jsonlint = require("jsonlint");

var $ = utils.getLocaleString;

exports.getGroup = function getGroup(client, name, callback) {
  client.resourceGroups.get(name, function(err, group) {
    if (err) {

      if ((err.statusCode === 404)) {
        callback(null, null); }
       else {

        callback(err); } ; }

     else {

      callback(null, group); } ; });};




exports.getResource = function getResource(client, resourceGroup, identity, callback) {
  client.resources.get(resourceGroup, identity.resourceProviderNamespace, identity.parentResourcePath, identity.resourceType, identity.resourceName, identity.resourceProviderApiVersion, function(err, resource) {





    if (err) {

      if ((err.statusCode === 404)) {
        callback(null, null); }
       else {

        callback(err); } ; }

     else {

      callback(null, resource); } ; });};




exports.createDeployment = function exports_createDeployment__1(cli, resourceGroup, name, options, _) { var subscription, client, templateParameters, templateName, baseTemplateName, result; var __frame = { name: "exports_createDeployment__1", line: 71 }; return __func(_, this, arguments, exports_createDeployment__1, 4, __frame, function __$exports_createDeployment__1() {
    subscription = profile.current.getSubscription(options.subscription);
    client = utils.createResourceClient(subscription);

    return createDeploymentParameters(cli, subscription, resourceGroup, options, __cb(_, __frame, 4, 27, function ___(__0, __2) { templateParameters = __2;


      if (!name) {
        templateName = (options.templateFile || options.templateUri);
        baseTemplateName = path.basename(templateName);

        if (utils.stringEndsWith(baseTemplateName, ".json", true)) {
          baseTemplateName = path.basename(baseTemplateName, path.extname(baseTemplateName)); } ;

        name = baseTemplateName; } ;


      return cli.interaction.withProgress($("Creating a deployment"), function __1(log, _) { var response; var __frame = { name: "__1", line: 89 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {

          return client.deployments.validate(resourceGroup, name, templateParameters, __cb(_, __frame, 1, 40, function ___(__0, __1) { response = __1;
            if (response.error) {
              log.error(util.format($("%s : %s"), response.error.code, response.error.message));
              if (response.error.details) {
                response.error.details.forEach(function(detail) {
                  displayNestedErrorDetailMessage(log, detail); }); } ;


              return _(new Error("Deployment validate failed.")); } ;


            return client.deployments.beginCreateOrUpdate(resourceGroup, name, templateParameters, __cb(_, __frame, 12, 32, _, true)); }, true)); }); }, __cb(_, __frame, 17, 31, function ___(__0, __3) { result = __3;


        cli.output.info(util.format($("Created template deployment \"%s\""), name));

        return _(null, result); }, true)); }, true)); });};



exports.validateTemplate = function exports_validateTemplate__2(cli, resourceGroup, options, log, _) { var subscription, client, templateParameters, response; var __frame = { name: "exports_validateTemplate__2", line: 110 }; return __func(_, this, arguments, exports_validateTemplate__2, 4, __frame, function __$exports_validateTemplate__2() {
    subscription = profile.current.getSubscription(options.subscription);
    client = utils.createResourceClient(subscription);

    return createDeploymentParameters(cli, subscription, resourceGroup, options, __cb(_, __frame, 4, 27, function ___(__0, __2) { templateParameters = __2;

      return cli.interaction.withProgress($("Validating the template"), function __1(log, _) { var __frame = { name: "__1", line: 117 }; return __func(_, this, arguments, __1, 1, __frame, function __$__1() {

          return client.deployments.validate(resourceGroup, "fakedDeploymentName", templateParameters, __cb(_, __frame, 1, 32, _, true)); }); }, __cb(_, __frame, 6, 33, function ___(__0, __3) { response = __3;


        response.requiredProviders = getTemplateProviders(response);

        if (response.error) {
          log.error(util.format($("%s : %s"), response.error.code, response.error.message));
          if (response.error.details) {
            response.error.details.forEach(function(detail) {
              displayNestedErrorDetailMessage(log, detail); }); } ; } ;




        return _(null, response); }, true)); }, true)); });};


exports.getTemplateDownloadUrl = function getTemplateDownloadUrl(templateData) {

  var urls = [];
  templateData.artifacts.forEach(function(e) {
    if ((e.type === "template")) {
      urls.push({
        name: e.name,
        uri: e.uri }); } ; });



  return urls;};


exports.getAllEvents = function(subscription, groupName) {
  var output = through();
  var client = utils.createEventsClient(subscription);

  client.eventData.listEventsForResourceGroup({
    resourceGroupName: groupName,
    startTime: new Date((Date.now() - eventRetentionPeriodMS)),
    endTime: new Date()
  }, function(err, response) {
    if (err) {
      return output.emit("error", err); } ;


    response.eventDataCollection.value.forEach(function(e) {
      output.queue(e); });

    output.end(); });

  return output;};


exports.getDeploymentLog = function(subscription, name, deploymentName) {
  var output = through();
  var client = utils.createResourceClient(subscription);

  client.deployments.get(name, deploymentName, function(err, result) {
    if (err) {
      return output.emit("error", err); } ;

    getDeploymentLogs(subscription, result.properties.correlationId).pipe(output); });

  return output;};


exports.getLastDeploymentLog = function(subscription, name) {
  var output = through();
  var client = utils.createResourceClient(subscription);

  client.deployments.list(name, { top: 1 }, function(err, response) {
    if (err) { return output.emit("error", err); } ;
    if ((response.length === 0)) {
      output.emit("error", new Error($("Deployment not found"))); } ;

    getDeploymentLogs(subscription, response[0].properties.correlationId).pipe(output); });

  return output;};


exports.normalizeDownloadFileName = function normalizeDownloadFileName(downloadFile, quiet, confirmer, callback) {
  function ensureDirExists(dirname) {
    if (!dirname) {
      return; } ;


    if (utils.pathExistsSync(dirname)) {
      if (!fs.statSync(dirname).isDirectory()) {
        throw new Error(util.format($("Path %s already exists and is not a directory."), dirname)); } ;

      return; } ;


    ensureDirExists(path.dirname(dirname));
    fs.mkdirSync(dirname); };


  try {
    ensureDirExists(path.dirname(downloadFile));
    if ((utils.pathExistsSync(downloadFile) && !quiet)) {
      confirmer(util.format($("The file %s already exists. Overwrite? [y/n]: "), downloadFile), function(err, confirmed) {


        if (confirmed) {
          callback(null, downloadFile); }
         else {
          callback(null, null); } ; }); }



     else {
      callback(null, downloadFile); } ;

  } catch (ex) {
    callback(ex); };};



function createDeploymentParameters(cli, subscription, resourceGroup, options, _) { var templateOptions, templateOptionsProvided, deploymentParameters, jsonFile, log, paramsRequired, templateParameters; var __frame = { name: "createDeploymentParameters", line: 235 }; return __func(_, this, arguments, createDeploymentParameters, 4, __frame, function __$createDeploymentParameters() {
    templateOptions = [options.templateFile,options.templateUri,];
    templateOptionsProvided = templateOptions.filter(function(value) { return (value !== undefined); }).length;
    if ((templateOptionsProvided > 1)) {
      return _(new Error($("Specify exactly one of the --template-file, or template-uri options."))); } else {
      if ((templateOptionsProvided === 0)) {
        return _(new Error($("One of the --template-file, or --template-uri options is required."))); } ; } ;


    if ((options.parameters && options.parametersFile)) {
      return _(new Error($("Either --parameters or --parameters-file need to be specified. Not both."))); } ; return (function __$createDeploymentParameters(__then) {



      if (options.parametersFile) {
        jsonFile = fs.readFileSync(options.parametersFile, "utf8");
        deploymentParameters = jsonlint.parse(utils.stripBOM(jsonFile));

        if (deploymentParameters.parameters) {
          deploymentParameters = deploymentParameters.parameters; } ; __then(); } else { return (function __$createDeploymentParameters(__then) {

          if (options.parameters) {
            deploymentParameters = jsonlint.parse(options.parameters); __then(); } else {

            log = cli.output;
            log.info("Supply values for the following parameters");
            return getTemplateParams(cli, subscription, options, __cb(_, __frame, 26, 25, function ___(__0, __3) { paramsRequired = __3;
              deploymentParameters = { };

              return Object.keys(paramsRequired).forEach_(__cb(_, __frame, 29, 32, __then, true), 1, function __1(_, key) { var val; var __frame = { name: "__1", line: 264 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() {
                  val = { };
                  val["value"] = paramsRequired[key];
                  deploymentParameters[key] = val; _(); }); }); }, true)); } ; })(__then); } ; })(function __$createDeploymentParameters() {




      templateParameters = { };
      if (options.mode) {
        templateParameters["properties"] = { mode: options.mode.toString() }; }

       else {
        templateParameters["properties"] = { mode: "Incremental" }; } ;


      if (options.debugSetting) {
        switch (options.debugSetting.toString().toLowerCase()) {
        case "requestcontent": templateParameters["properties"]["debugSetting"] = {
            detailLevel: "RequestContent" }; break;
        case "responsecontent":

          templateParameters["properties"]["debugSetting"] = {
            detailLevel: "ResponseContent" }; break;
        case "all":

          templateParameters["properties"]["debugSetting"] = {
            detailLevel: "RequestContent,ResponseContent" }; break;
          default:

          break;
        }; } ;



      return cli.interaction.withProgress($("Initializing template configurations and parameters"), function __2(log, _) { var templateUri, templateContent; var __frame = { name: "__2", line: 300 }; return __func(_, this, arguments, __2, 1, __frame, function __$__2() {


          templateUri = options.templateUri; return (function __$__2(__then) {
            if (!templateUri) {
              return getTemplateContent(subscription, options.templateFile, __cb(_, __frame, 4, 30, function ___(__0, __1) { templateContent = __1;
                templateParameters["properties"]["template"] = templateContent; __then(); }, true)); } else {

              templateParameters["properties"]["templateLink"] = { uri: templateUri };
              if (options.templateVersion) {
                templateParameters.properties.templateLink.contentVersion = options.templateVersion; } ; __then(); } ; })(function __$__2() {



            if (deploymentParameters) {
              templateParameters.properties.parameters = deploymentParameters; } ; _(); }); }); }, __cb(_, __frame, 64, 18, function __$createDeploymentParameters() {



        return _(null, templateParameters); }, true)); }); });};


var eventRetentionPeriodMS = ((((89 * 24) * 60) * 60) * 1000);

function getDeploymentLogs(subscription, correlationId) {
  var output = through();
  var client = utils.createEventsClient(subscription);
  client.eventData.listEventsForCorrelationId({
    correlationId: correlationId,
    startTime: new Date((Date.now() - eventRetentionPeriodMS)),
    endTime: new Date()
  }, function(err, response) {
    if (err) {
      return output.emit("error", err); } ;

    response.eventDataCollection.value.forEach(function(e) {
      output.queue(e); });

    output.end(); });

  return output;};


function getTemplateProviders(validationResponse) {
  if ((validationResponse.properties && validationResponse.properties.providers)) {
    return __.map(validationResponse.properties.providers, function(provider) {
      if (provider.namespace) {
        return provider.namespace.toLowerCase(); } ; }); } ;};





function getTemplateContent(subscription, templateFile, _) { var templateFileUri, content;
  function readTemplateFileContentFromUri(templateFileUri, callback) {
    request(templateFileUri, function(error, response, body) {
      callback(error, body); }); }; var __frame = { name: "getTemplateContent", line: 352 }; return __func(_, this, arguments, getTemplateContent, 2, __frame, function __$getTemplateContent() {




    if (templateFile) {
      if (validation.isURL(templateFile)) {
        templateFileUri = templateFile; } ; } ;



    content = { }; return (function __$getTemplateContent(__then) {
      if (templateFileUri) {
        return readTemplateFileContentFromUri(templateFileUri, __cb(_, __frame, 16, 14, function ___(__0, __1) { content = __1; __then(); }, true)); } else {
        if (templateFile) {
          content = utils.stripBOM(fs.readFileSync(templateFile)); } ; __then(); } ; })(function __$getTemplateContent() {


      return _(null, jsonlint.parse(content)); }); });};


function getTemplateParams(cli, subscription, options, _) { var templateContent, paramKeys; var __frame = { name: "getTemplateParams", line: 376 }; return __func(_, this, arguments, getTemplateParams, 3, __frame, function __$getTemplateParams() { return (function __$getTemplateParams(_) {

      var __2 = options.templateFile; return (function __$getTemplateParams(__then) { if (__2) {
          return getTemplateContent(subscription, options.templateFile, __cb(_, __frame, 3, 4, _, true)); } else { __then(); } ; })(function __$getTemplateParams() {
        return getTemplateContent(subscription, options.templateUri, __cb(_, __frame, 4, 4, _, true)); }); })(__cb(_, __frame, -375, 17, function ___(__0, __3) { templateContent = __3;

      paramKeys = { }; return (function __$getTemplateParams(__then) {
        if (templateContent.parameters) {
          return Object.keys(templateContent.parameters).forEach_(__cb(_, __frame, 8, 44, __then, true), 1, function __1(_, param) { var __frame = { name: "__1", line: 384 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() {
              paramKeys[param] = templateContent.parameters[param].defaultValue; return (function __$__1(__then) {
                if (!templateContent.parameters[param].defaultValue) {
                  return cli.interaction.promptIfNotGiven((param + ": "), paramKeys[param], __cb(_, __frame, 3, 43, function ___(__0, __1) { paramKeys[param] = __1;
                    switch (templateContent.parameters[param].type.toLowerCase()) {
                    case "int": paramKeys[param] = utils.parseInt(paramKeys[param]);
                      break;
                    case "object":

                    
                    case "bool": 
                    case "array": paramKeys[param] = jsonlint.parse(paramKeys[param]);
                      break;
                    }; __then(); }, true)); } else { __then(); } ; })(_); }); }); } else { __then(); } ; })(function __$getTemplateParams() {





        return _(null, paramKeys); }); }, true)); });};


exports.getFailedDeploymentOperations = function exports_getFailedDeploymentOperations__3(subscription, resourceGroup, deploymentName, _) { var currentSubscription, client, operations, failedOperations; var __frame = { name: "exports_getFailedDeploymentOperations__3", line: 406 }; return __func(_, this, arguments, exports_getFailedDeploymentOperations__3, 3, __frame, function __$exports_getFailedDeploymentOperations__3() {
    currentSubscription = profile.current.getSubscription(subscription);
    client = utils.createResourceClient(currentSubscription);
    return client.deploymentOperations.list(resourceGroup, deploymentName, __cb(_, __frame, 3, 47, function ___(__0, __1) { operations = __1;
      return getFailedNestedOperations(client, resourceGroup, operations, __cb(_, __frame, 4, 25, function ___(__0, __2) { failedOperations = __2;
        return _(null, failedOperations); }, true)); }, true)); });};


function getFailedNestedOperations(client, resourceGroup, currentOperations, _) { var newOperations; var __frame = { name: "getFailedNestedOperations", line: 414 }; return __func(_, this, arguments, getFailedNestedOperations, 3, __frame, function __$getFailedNestedOperations() {
    newOperations = [];
    return currentOperations.forEach_(__cb(_, __frame, 2, 20, function __$getFailedNestedOperations() {











      return _(null, newOperations); }, true), 1, function __1(_, operation) { var nestedDeployment, nestedOperations, newNestedOperations; var __frame = { name: "__1", line: 416 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { return (function __$__1(__then) { if ((operation.properties.provisioningState === "Failed")) { newOperations.push(operation); return (function __$__1(__then) { if ((operation.properties.targetResource && (operation.properties.targetResource.id.indexOf("Microsoft.Resources/deployments") !== -1))) { nestedDeployment = operation.properties.targetResource.resourceName; return client.deploymentOperations.list(resourceGroup, nestedDeployment, __cb(_, __frame, 6, 59, function ___(__0, __1) { nestedOperations = __1; return getFailedNestedOperations(client, resourceGroup, nestedOperations, __cb(_, __frame, 7, 34, function ___(__0, __2) { newNestedOperations = __2; newOperations = newOperations.concat(newNestedOperations); __then(); }, true)); }, true)); } else { __then(); } ; })(__then); } else { __then(); } ; })(_); }); }); });};


function displayNestedErrorDetailMessage(log, detail) {
  if ((detail.code && detail.message)) {
    log.error(util.format($("%s : %s"), detail.code, detail.message));
    if (detail.details) {
      detail.details.forEach(function(innerDetail) {
        displayNestedErrorDetailMessage(log, innerDetail); }); } ; } ;};
