'use strict';

(({ App }) => {
  const VARIABLE_PATTERN = /VAR_([A-Z0-9_]+)/g;
  const GLOBAL_VARIABLE_PATTERN = /PSet\("basglobal"\s*,\s*"([^"]+)"\s*,/g;
  const EXTENDED_VARIABLE_PATTERN = /VAR_([A-Z0-9_]+)\s*[+\-*\/%]?=\s*[^=<>]/g;
  const ERROR_VARIABLES = /* Ignore Errors */ ['ERROR_ID', 'WAS_ERROR', 'LAST_ERROR'];

  App.Inspector.utils.getVariablesList = (id, strict = false) => {
    const task = FindTaskById(id);
    if (!task) return [];

    const variables = [];
    const dat = task.dat();
    const code = task.get('code');
    const isEmbedded = dat && dat.s && dat.s.includes('EmbeddedLanguages');

    if (dat && dat.d) {
      for (const item of dat.d) {
        if (item.data && item.type === 'var' && item.id !== 'ResourceName' && typeof item.data === 'string') {
          if (item.data.includes(',')) {
            for (const variable of item.data.split(',')) {
              variables.push(variable.trim());
            }
          } else {
            variables.push(
              dat.s && (dat.s.includes('globalset') || dat.s.includes('incglobalvariable'))
                ? `GLOBAL:${item.data}`
                : item.data
            );
          }
        }
      }
    }

    // If strict mode is enabled, error-related variables
    // should only be added if the target action changes them:
    const matches = new Set([
      ...variables,
      ...(strict ? [] : ERROR_VARIABLES),
      ...Array.from(code.matchAll(GLOBAL_VARIABLE_PATTERN), (match) => `GLOBAL:${match[1]}`),
      ...Array.from(code.matchAll(isEmbedded ? VARIABLE_PATTERN : EXTENDED_VARIABLE_PATTERN), (match) => match[1]),
    ]);

    return [...matches];
  };
})(window);
