/**
 * Created by baoyinghai on 10/25/16.
 */
const reg = /\${\w*}/g;
const dic = /^[A-Z_]*$/;

const getKey = key => {
  if (key.length > 2) {
    return key.substring(2, key.length - 1);
  }
  return '';
};

export const firstUpperCase = str => str.replace(/\b(\w)(\w*)/g, ($0, $1, $2) => $1.toUpperCase() + $2.toLowerCase());

const transformValue = (value, mappings) => {
  const result = mappings && mappings.reduce((obj, item) => {
    obj[item.dictionaryItemName] = item.serviceName;
    return obj;
  }, {})[value];
  if (result) {
    return result;
  }
  if (dic.test(value)) {
    return value.split('_').map(str => firstUpperCase(str)).join('');
  }
  return value;
};

export const toLowerFirstCase = str => str && str.replace(/(\w)/, v => v.toLowerCase());

export const convertTemplate = (template = '', params = {}, mappings) => (template.match(reg) || []).reduce((temp = '', key) => temp.replace(key, transformValue(params[getKey(key || '')], mappings || []) || ''), template);

export const isArray = obj => Object.prototype.toString.call(obj) === '[object Array]';

export const trimStart = (str, chars) => {
  if (str[0] === chars) {
    return str.substring(1);
  }
  return str;
};

export const templateReg = reg;

export const getTemplateFields = (template = '') => (template.match(reg) || []).map(item => item.substring(2, item.length - 1));

export const trimStartAndEnd = str => str.replace(/(^\s*)|(\s*$)/g, '');
