/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

// lazy-load; timing issues
let signatures;

module.exports = class Signature {
  /**
   * Create a Signature.
   *
   * @param {string|object} sig - If a string, we'll try to look up the sig object
   *								for this value in the policy.
   */
  constructor(sig) {
    if (typeof sig === 'string') {
      if (!signatures) {
        ({ signatures } = require('../policy/signatures.json'));
      }

      sig = signatures[sig];
    }

    if (sig) {
      this.moduleName = sig.moduleName;
      this.methodName = sig.methodName;
      this.isModule = sig.isModule;

      // very few things pass this in themselves
      this.args = sig.args;
      this.return = sig.return;
    }
  }

  /**
   * Gives the signature the properties expected by TS
   */
  format(args, result) {
    switch (this.methodName) {
      case '__add':
        this.moduleName = 'native_operator';
        this.methodName = 'plus';
        break;
      case '__contrastEval':
        this.moduleName = 'global';
        this.methodName = 'eval';
        break;
      case 'ContrastFunction':
        this.moduleName = 'global';
        this.methodName = 'Function';
        break;
      default:
        break;
    }

    this.argTypes = Signature.getArgTypes(args);
    this.returnType = Signature.getType(result);
    this.className = this.moduleName;
  }

  /**
   * Loops through args, finding and assigning type names
   */
  static getArgTypes(args) {
    return args.map(function(arg) {
      return Signature.getType(arg);
    });
  }

  /**
   * Assigns type names for signatures
   */
  static getType(obj) {
    if (typeof obj === 'undefined') {
      return 'undefined';
    }

    return obj.constructor.name;
  }
};
