'use strict';
let path = require('path');

let _ = require('lodash');
let retry = require('retry');
let es = require('elasticsearch');

function createTemplate(client, templateName, templateDir, overwrite) {
  let fn = (resolve, reject) => {
    let params = {name: templateName};

    return client.indices.existsTemplate(params)
    .then(exists => {
      if (!exists || overwrite) {
        params.body = require(path.join(templateDir, templateName + '.json'));

        client.indices.putTemplate(params)
          .then(() => resolve(true))
          .catch(err => {
            reject(new Error(`Failed writing template '${templateName}': ${err.message}`));
          });
          ;
      } else {
        resolve(false);
      }
    })
    .catch(err => {
      reject(new Error(`Failed checking if template '${templateName}' exists: ${err.message}`));
    });
  }

  return new Promise(fn);
}

function faultTolerantCreateTemplate(client, templateName, templateDir, overwrite, retries) {
  let fn = (resolve, reject) => {
    let opts;

    /**
     * Default to no retries rather than 10 (the module's default):
     */

    opts = {retries: retries || 0};

    let operation = retry.operation(opts);

    operation.attempt(() => {
      createTemplate(client, templateName, templateDir, overwrite)
      .then(resolve)
      .catch(err => {
        if (!operation.retry(err)) {
          reject(err);
        }
      })
      ;
    });
  };

  return new Promise(fn);
}

let promise = _opts => {
  let manageTemplate = (resolve, reject) => {
    let opts = _.clone(_opts);
    let manageTemplate = (!('manageTemplate' in opts) || opts.manageTemplate);

    if (!manageTemplate) {
      resolve(false);
    } else {
      if (opts.amazonES) {
        opts.connectionClass = require('http-aws-es');
      }

      let client = new es.Client(opts);

      if (!opts.templateName) {
        reject(new Error('Missing templateName parameter'));
      } else {
        opts.templateName.split(/\s*,\s*/).forEach(name => {
          faultTolerantCreateTemplate(client, name, opts.templateDir,
            opts.templateOverwrite, opts.retries)
          .then(resolve)
          .catch(reject)
          ;
        });
      }
    }
  }

  return new Promise(manageTemplate);
};

module.exports = {
  promise
};

@@ -34,16 +34,45 @@
 'path');
+%0Alet h = require('highland');
 %0A%0Alet _ 
@@ -2305,16 +2305,681 @@
 e);%0A%7D;%0A%0A
+let stream = function(_opts) %7B%0A  let doneTemplate = false;%0A%0A  return s =%3E %7B%0A    return s.consume((err, x, push, next) =%3E %7B%0A      if (err) %7B%0A        push(err);%0A        next();%0A      %7D%0A      else if (x === h.nil) %7B%0A        push(null, x);%0A      %7D%0A      else %7B%0A        if (doneTemplate) %7B%0A          push(null, x);%0A          next();%0A        %7D else %7B%0A          doneTemplate = true;%0A          promise(_opts)%0A          .then(() =%3E %7B%0A            push(null, x);%0A            next();%0A          %7D)%0A          .catch(err =%3E %7B%0A            push(new Error(%60manageTemplate failed: $%7Berr.message%7D%60));%0A            next();%0A          %7D)%0A          ;%0A        %7D%0A      %7D%0A    %7D)%0A    ;%0A  %7D%0A%7D;%0A%0A
 module.e
@@ -2998,12 +2998,22 @@
  promise
+,%0A  stream
 %0A%7D;%0A

add stream version of managetemplate