var querystring = require('querystring');
var _ = require('underscore');
var http = require('http');

exports.index = function(req, res) {
  res.render('index');
};

function withDomain(req, res, callback) {
  var domain = _.where(res.locals.domains, {DomainName: req.params.name})[0];
  domain.isSelected = true;

  req.domain = domain;

  // get index fields
  req.cloudsearch.DescribeIndexFields({
    DomainName: domain.DomainName
  }, function(error, data) {
    if (error) {
      res.status(500);
      res.render('error', {message: error.Message});
      return;
    }
    var indexFields = convertToArray(data.Body.DescribeIndexFieldsResponse.DescribeIndexFieldsResult.IndexFields.member);
    var indexFieldNames = indexFields.map(function(indexField) {
      return indexField.Options.IndexFieldName;
    });

    req.indexFields = indexFields;
    callback(req, res);
  });

  return domain;
}

function convertToArray(data) {
  // awssum returns undefined for 0 item, object itself for 1 item,
  // array for >1 items. Make all of them as a Array.
  if (!data) {
    return [];
  } else if (!(data instanceof Array)) {
    return [data];
  } else {
    return data;
  }
}

exports.domain = function(req, res) {
  withDomain(req, res, function(req, res) {
    res.render('domain-show', {
      domain: req.domain,
      indexFields: req.indexFields
    });
  });
};

exports.domainSearch = function(req, res) {
  withDomain(req, res, function(req, res) {
    var query = req.query.query;
    var size = 10;
    var start = 0; // TODO support paginate

    if (query === undefined) {
      var locals = {
        domain: req.domain,
        query: null,
        requestURL: null,
        results: null
      };
      res.render('domain-search', locals);
      return;
    }

    var indexFieldNames = req.indexFields.map(function(indexField) {
      return indexField.Options.IndexFieldName;
    });

    var paramsForSearch = {
      q: query,
      size: size,
      start: start,
      'return-fields': indexFieldNames.join(',')
    };
    var requestURL = 'http://' + req.domain.SearchService.Endpoint + '/2011-02-01/search?' + querystring.stringify(paramsForSearch);

    var buffer = '';
    var results = null;
    http.get(requestURL, function(searchResponse) {
      searchResponse.setEncoding('utf8');
      searchResponse.on('data', function (chunk) {
        buffer += chunk;
      });
      searchResponse.on('end', function() {
        var locals = {
          domain: req.domain,
          query: query,
          requestURL: requestURL,
          results: JSON.parse(buffer),
          start: start
        };
        res.render('domain-search', locals);
      });
    });
    // TODO handle errors
  });
};

exports.domainCreate = function(req, res) {
  res.render('domain-create', {domain: null});
};

exports.domainCreatePost = function(req, res) {
  var domainName = req.body.domain_name;
  req.cloudsearch.CreateDomain({
    DomainName: domainName
  }, function(error, data) {
    if (error) {
      // TODO redirect back domainCreate if it is a kind of validation error
      // TODO render error in a more pretty way
      // TODO in some cases, the error should be 400 rather than 500
      res.status(500);
      var message = JSON.stringify(error.Body.Response.Errors);
      res.render('error', {message: message});
      return;
    }

    var domainCreated = data.Body.CreateDomainResponse.CreateDomainResult.DomainStatus;
    res.redirect('/domain/'+domainCreated.DomainName);
  });
};

exports.domainDelete = function(req, res) {
  withDomain(req, res, function(req, res) {
    req.cloudsearch.DeleteDomain({
      DomainName: req.domain.DomainName
    }, function(error, data) {
      if (error) {
        // TODO redirect back domainCreate if it is a kind of validation error
        // TODO render error in a more pretty way
        // TODO in some cases, the error should be 400 rather than 500
        res.status(500);
        var message = JSON.stringify(error.Body.Response.Errors);
        res.render('error', {message: message});
        return;
      }

      res.redirect('/');
      // TODO some feedback to user may be needed
    });
  });
};

@@ -695,129 +695,8 @@
 er);
-%0A    var indexFieldNames = indexFields.map(function(indexField) %7B%0A      return indexField.Options.IndexFieldName;%0A    %7D);
 %0A%0A  

Remove unused code