'use strict';

(({ App }) => {
  let pendingRequest = Promise.resolve();

  App.Inspector.utils.executeExpression = async (expression, { isVariable, isString, timeout, noTruncate } = {}) => {

    const loader = new ResourceLoader();
    loader.SetIsString(isString);
    loader.SetIsVariable(isVariable);
    loader.SetModifiersOverride(false, true);

    expression = loader.Resolve(`${expression}`);
    if (!expression) return { result: expression };

    if (!App.Inspector.utils.isValidExpression(expression)) {
      return { error: 'INVALID_EXPRESSION' };
    }

    return await (pendingRequest = pendingRequest.then(() => {
      return new Promise((resolve) => {
        const functionName = (noTruncate) ? "execute_expression_no_truncate" : "execute_expression";
        const code = `
          try {
            ${loader.GetAdditionalDataInstant()};
            _execute_sync_result("-BAS-EXECUTESYNC-ID-", ${functionName}(${JSON.stringify(
              utf8_to_b64(`(${expression});`)
            )}))
          }catch (e) {
            _execute_sync_result("-BAS-EXECUTESYNC-ID-", {"error": e.message})
          }
        `
        BrowserAutomationStudio_ExecuteSyncCode(code, timeout).then(({ result, was_timeout }) =>{
          if(was_timeout)
          {
            resolve({ error: 'Timeout during expression execution' })
            return;
          }
          resolve(App.utils.parseJSON(result))
        } )

      });
    }));
  };
})(window);
