import Ember from 'ember';
import { helper } from 'ember-helper';
import { htmlSafe } from 'ember-string';

// eslint-disable-next-line ember-rules/destructure-namespaces
const { escapeExpression } = Ember.Handlebars.Utils;

const ASCII_RANGE_REGEX = /^[\x00-\x7F]*$/; // eslint-disable-line no-control-regex

export function formatDisplayName(login, displayName, noHtml) {
  noHtml = noHtml || false;
  if (displayName && login && !isAscii(displayName)) {
    displayName = escapeExpression(displayName);
    login = escapeExpression(login);
    if (noHtml) {
      return htmlSafe(`${displayName} (${login})`);
    }
    return htmlSafe(`${displayName} <span class='intl-login'>(${login})</span>`);
  } else if (displayName) {
    return displayName;
  }
  return login;
}

export default helper((args) => formatDisplayName(...args));

//Checks if all characters in the string are in the ascii range 0 - 127.
export function isAscii(str) {
  return ASCII_RANGE_REGEX.test(str); 
}
