/**
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';
const tagUtil = require('../models/tag-range/util');
const TagRange = require('../models/tag-range');
const tracker = require('../../tracker');
const Membrane = require('./index');
const { PropagationEvent, Signature, CallContext } = require('../models');

const signature = new Signature('JSON.parse');

class DeserializationMembrane extends Membrane {
  /**
   * @param {Object} data patcher data
   * @param {ContrastProperties} props the metadata associated with the string which was deserialized to create the object in this membrane
   */
  constructor(data, props) {
    super();
    // use result for object and result because the object would just
    // be stringified for display anyway. not exact, but close enough.
    this.result = data.result;
    this.arg = data.args[0];
    this.obj = data.result;
    this.event = props.event;
    this.tagRanges = tagUtil.filterNonSupersetGroups(
      'untrusted',
      props.tagRanges
    );
  }

  onString(str, metadata) {
    const context = CallContext.create({
      obj: this.obj,
      args: [this.arg],
      result: this.result,
      stackOpts: {
        constructorOpt: this.wrap
      }
    });
    const event = new PropagationEvent({
      context,
      signature,
      tagRanges: this.tagRanges,
      source: 'A',
      target: 'R'
    });

    const tracked = tracker.track(str);

    if (!tracked) {
      return str;
    }

    tracked.props.event = event;
    event.parents.push(this.event);
    tracked.props.tagRanges = this.tagRanges.map(
      (t) => new TagRange(0, str.length - 1, t.tag)
    );

    return tracked.str;
  }
}

module.exports = DeserializationMembrane;
