/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var __ = require('underscore');

var interaction = require('../util/interaction');
var utils = require('../util/utils');

exports.init = function (cli) {

  var log = cli.output;
  var site = cli.category('site');
  var siteDefaultDocument = site.category('defaultdocument')
    .description('Commands to manage your Web Site default documents');

  siteDefaultDocument.command('list [name]')
    .usage('[options] [name]')
    .description('Show your site default documents')
    .option('-s, --subscription <id>', 'use the subscription id')
    .execute(function (name, options, _) {
      var context = {
        subscription: cli.category('account').lookupSubscriptionId(options.subscription),
        site: { name: name }
      };

      site.lookupSiteNameAndWebSpace(context, _);

      var siteConfigurations = site.doSiteConfigGet(context, _);
      if (siteConfigurations.DefaultDocuments && siteConfigurations.DefaultDocuments['a:string']) {
        siteConfigurations = {
          '$': siteConfigurations['$'],
          DefaultDocuments: getDefaultDocuments(siteConfigurations.DefaultDocuments)
        };

        log.table(siteConfigurations.DefaultDocuments['a:string'], function (row, item) {
          row.cell('Name', item);
        });
      } else {
        log.info('No default documents defined yet.');
      }
    });

  siteDefaultDocument.command('add [document] [name]')
    .usage('[options] [name]')
    .description('Add a site default document')
    .option('-d, --document <document>', 'the new default document')
    .option('-s, --subscription <id>', 'use the subscription id')
    .execute(function (document, name, options, _) {
      var context = {
        subscription: cli.category('account').lookupSubscriptionId(options.subscription),
        site: { name: name }
      };

      var params = utils.normalizeParameters({
        document: [document, options.document]
      });

      if (params.err) { throw params.err; }

      document = interaction.promptIfNotGiven(cli, 'Document: ', params.values.document, _);

      site.lookupSiteNameAndWebSpace(context, _);

      var siteConfigurations = site.doSiteConfigGet(context, _);
      siteConfigurations.DefaultDocuments = getDefaultDocuments(siteConfigurations.DefaultDocuments);
      siteConfigurations.DefaultDocuments['a:string'].push(document);
      site.doSiteConfigPUT(siteConfigurations, context, _);
    });

  siteDefaultDocument.command('delete [document] [name]')
    .usage('[options] [name]')
    .description('Deletes a site default document')
    .option('-d, --document <document>', 'the new default document')
    .option('-s, --subscription <id>', 'use the subscription id')
    .execute(function (document, name, options, _) {
      var context = {
        subscription: cli.category('account').lookupSubscriptionId(options.subscription),
        site: { name: name }
      };

      var params = utils.normalizeParameters({
        document: [document, options.document]
      });

      if (params.err) { throw params.err; }

      document = interaction.promptIfNotGiven(cli, 'Document: ', params.values.document, _);

      site.lookupSiteNameAndWebSpace(context, _);

      var siteConfigurations = site.doSiteConfigGet(context, _);

      var found = false;
      if (siteConfigurations.DefaultDocuments && siteConfigurations.DefaultDocuments['a:string']) {
        siteConfigurations.DefaultDocuments = getDefaultDocuments(siteConfigurations.DefaultDocuments);

        for (var i = 0; i < siteConfigurations.DefaultDocuments['a:string'].length; i++) {
          if (utils.ignoreCaseEquals(siteConfigurations.DefaultDocuments['a:string'][i], document)) {
            siteConfigurations.DefaultDocuments['a:string'].splice(i, 1);
            found = true;
            i--;
          }
        }

        if (found) {
          if (siteConfigurations.DefaultDocuments['a:string'].length === 0) {
            siteConfigurations.DefaultDocuments = { };
          }

          site.doSiteConfigPUT(siteConfigurations, context, _);
        }
      }

      if (!found) {
        throw new Error('Default document "' + document + '" does not exist.');
      }
    });

  function getDefaultDocuments(defaultDocuments) {
    if (!defaultDocuments) {
      defaultDocuments = {
        '$': {
          'xmlns:a': 'http://schemas.microsoft.com/2003/10/Serialization/Arrays'
        }
      };
    }

    if (!defaultDocuments['a:string']) {
      defaultDocuments['a:string'] = [ ];
    } else if (!__.isArray(defaultDocuments['a:string'])) {
      defaultDocuments['a:string'] = [ defaultDocuments['a:string'] ];
    }

    return defaultDocuments;
  }
};
@@ -2059,35 +2059,72 @@
 default document
+ (by default, to the end of the list)
 ')%0A
-
     .option('-d,
@@ -2168,32 +2168,117 @@
 ault document')%0A
+    .option('-p, --position %3Cposition%3E', 'the position of the new default document')%0A
     .option('-s,
@@ -2993,16 +2993,613 @@
 ments);%0A
+%0A      if (siteConfigurations.DefaultDocuments%5B'a:string'%5D.indexOf(document) %3E -1) %7B%0A        throw new Error('Duplicate default document');%0A      %7D%0A%0A      if (options.position) %7B%0A        if (options.position %3E siteConfigurations.DefaultDocuments%5B'a:string'%5D.length) %7B%0A          throw new Error(util.format('Provided position %25s is larger than current default document number %25s', options.position, siteConfigurations.DefaultDocuments%5B'a:string'%5D.length));%0A        %7D else %7B%0A          siteConfigurations.DefaultDocuments%5B'a:string'%5D.splice(options.position, 0, document);%0A        %7D%0A      %7D else %7B%0A  
       si
@@ -3656,24 +3656,33 @@
 (document);%0A
+      %7D%0A%0A
       site.d

Apply code review