import { upperFirst, camelCase, logger } from '../utils';

export function parseExpression(str: any, self: any, thisRequired = false) {
  try {
    const contextArr = ['"use strict";', 'var __self = arguments[0];'];
    contextArr.push('return ');
    let tarStr: string = (str.value || '').trim();
    tarStr = tarStr.replace(/this(\W|$)/g, (_a: any, b: any) => `__self${b}`);
    tarStr = contextArr.join('\n') + tarStr;
    const code = `with(${thisRequired ? '{}' : '$scope || {}'}) { ${tarStr} }`;
    return new Function('$scope', code)(self);
  } catch (err) {
    logger.error('parseExpression.error', err, str, self?.__self ?? self);
  }
}

export function parseFunction(str: any, self: any, thisRequired = false) {
  const fn = parseExpression(str, self, thisRequired);
  if (typeof fn !== 'function') {
    logger.error(
      'parseFunction.error',
      'not a function',
      str,
      self?.__self ?? self
    );
  }
  return fn;
}

export function upperFirstCamelCase(word: string) {
  return upperFirst(camelCase(word));
}
