import { hasOwn } from 'press-ui/common/utils/object-base';

const STRING_FORMAT_REG = /(%|)\{\{([0-9a-zA-Z_]+)\}\}/g;
/**
 *  String format template
 *  - Inspired:
 *    https://github.com/Matt-Esch/string-template/index.js
 */
export default function stringFormat(string: string, ...args: any) {
  if (args.length === 1 && typeof args[0] === 'object') {
    args = args[0];
  }

  if (!args?.hasOwnProperty) {
    args = {};
  }

  return string.replace(STRING_FORMAT_REG, (match, prefix, i, index) => {
    if (string[index - 1] === '{'
        && string[index + match.length] === '}') {
      return i;
    }
    const result = hasOwn(args, i) ? args[i] : null;
    if (result === null || result === undefined) {
      return '';
    }

    return result;
  });
}
