/**
 * Inspired by gulp-angular-translate by RobbinHabermehl
 * License: MIT
 * */

var concat = require('gulp-concat');
var es = require('event-stream');
var gutil = require('gulp-util');

function cacheTranslations(options) {
  return es.map(function(file, callback) {
    var template = '    {key: "<%= langcode %>", language: "<%= langname %>", dir: "<%= direction %>"},';
    var json = JSON.parse(file.contents.toString());
    var langname = json["META_LANGUAGE"];

    var direction = "ltr";
    if ("META_DIRECTION" in json) {
      direction = json["META_DIRECTION"];
    }
    var langcode = file.path.split('/').pop().match(/^([a-z]+[_|-]?(?:[A-Z]+)?)\.json$/i).pop();

    file.contents = new Buffer(gutil.template(template, {
      langname: langname,
      file: file,
      langcode: langcode,
      direction: direction
    }));

    if (langcode === "qqq") {
      callback();
    } else {
      callback(null, file);
    }
  });
}

function wrapTranslations(options) {
  var template =
    '\'use strict\';\n' +
    '/** This file was autogenerated by gulp task i18n-autogenerate **/\n' +
    'angular\n' +
    '  .module(\'<%= module %>\')\n' +
    '  .constant(\'translationList\', [\n' +
    '<%= contents %>\n' +
    '  ]\n' +
    ');';
  return es.map(function(file, callback) {
    file.contents = new Buffer(gutil.template(template, {
      contents: file.contents,
      file: file,
      module: options.module || 'translate'
    }));
    callback(null, file);
  });
}

function crosswatchTranslate(filename, options) {
  if (typeof filename === 'string') {
    options = options || {};
  } else {
    options = filename || {};
    filename = options.filename || 'translations.js';
  }
  return es.pipeline(
    cacheTranslations(options),
    concat(filename),
    wrapTranslations(options)
  );
}

module.exports = crosswatchTranslate;
