/* globals i18n */
import Ember from 'ember';
import { typeOf } from 'ember-utils';
import { helper } from 'ember-helper';
import { htmlSafe } from 'ember-string';

const { Handlebars: { Utils: { escapeExpression } } } = Ember;

/*
  Basic helper for interpolating HTML elements onto translated strings.

  * Supports key-value replacement (with objects or arrays, but not both at once)
  * Supports only one styling -- bolding various elements with $start-bold$ and $end-bold$
  * Performs zero validation, so the resulting string may be invalid HTML.

  Usage:
    Simple cases:
      {{styled-i18n "look, bold! $start-bold$So bold!$end-bold"}} --> "look, bold! <div class='strong'>So bold!</div>"
      {{styled-i18n "look, replaced! %{0} %{1} %{2}" "first" "second" "third"}} --> "look, replaced! first second third"
      {{styled-i18n "hash replace! %{first} %{second}" (hash first='a' second='b')}} --> "hash replace! a b"

    You can mix and match style and value replacements as necessary.
    You cannot mix and match index/array based replacement and hash based variable replacement.
*/

export function stringFormat(string, values) {
  if (!values) {
    return string;
  }

  let keys = Object.keys(values);
  if (keys.length > 0) {
    keys.forEach(key => {
      let value = escapeExpression(values[key]);
      let regex = new RegExp(`\\%\\{${key}\\}`, 'g');

      string = string.replace(regex, value);
    });
  }

  return string;
}

export function processStyling(string) {
  return string
    .replace(/\$start-bold\$/g, '<span class="strong">')
    .replace(/\$end-bold\$/g, '</span>');
}

// Styled, safe
export function styledI18n(string, values) {
  let i18nString = i18n(string);

  /* Process styling */
  i18nString = processStyling(i18nString);
  i18nString = stringFormat(i18nString, values);

  return htmlSafe(i18nString);
}

// Unstyled, non-safe
export function formattedI18n(string, values) {
  let i18nString = i18n(string);

  return stringFormat(i18nString, values);
}

// Helper base function
let styledI18nHelper = function([string, ...args]) {
  let values;

  if (args && args[0] && typeOf(args[0]) === 'object') {
    values = args[0];
  } else {
    values = args;
  }

  return styledI18n(string, values);
};

export default helper(styledI18nHelper);
