/**
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 constants = require('../../../constants');
const { DOCUMENT_TYPES, INPUT_TYPES } = constants;

module.exports = class UserInput {
  constructor(info = {}) {
    this.time = new Date().getTime();
    this.documentPath = info.path;
    this.documentType = info.type;
    this.type = info.type;
    this.name = info.name;
    this.value = info.value;
  }

  set documentPath(path) {
    this._documentPath = path || '';
  }

  get documentPath() {
    return this._documentPath;
  }

  set documentType(type) {
    this._documentType = type;
  }

  get documentType() {
    return this._documentType === INPUT_TYPES.JSON_VALUE
      ? DOCUMENT_TYPES.JSON
      : this._documentType === INPUT_TYPES.XML_VALUE
      ? DOCUMENT_TYPES.XML
      : DOCUMENT_TYPES.NORMAL;
  }

  set name(name) {
    this._name = name || '';
  }
  /*
    Note: URI-type `UserInput`s don't have a `name` in the way that a JSON or querysting
    value would. But, we set it to URL to support evaluation of the UserInput
    by processes within virtual patches and input exclusions.
  */
  get name() {
    return this._type === 'URI' ? 'URL' : this._name;
  }

  set type(type) {
    this._type = type;
  }

  get type() {
    return this._type in INPUT_TYPES ? this._type : INPUT_TYPES.UNKNOWN;
  }

  set value(value) {
    this._value = value || '';
  }

  get value() {
    return this._value.toString();
  }

  toSerializable() {
    return {
      time: this.time,
      documentPath: this.documentPath.replace(/\./g, '>'),
      documentType: this.documentType,
      type: this.type,
      name: this.name,
      value: this.value
    };
  }
};
