/**
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 {
  PATCH_TYPES,
  HTTP_RESPONSE_HOOKED_METHOD_KEYS,
  SINK_TYPES
} = require('../../constants');
const patcher = require('../patcher');
const HttpFramework = require('./http');
const { isString } = require('../../util/is-string');
const { emitSendEvent } = require('../../hooks/frameworks/common');
const agentEmitter = require('../../agent-emitter');

class SpdyFramework extends HttpFramework {
  /**
   * @param {Agent} agent
   */
  constructor(agent) {
    super(agent, 'spdy');
  }

  /**
   * @param {import('spdy')} spdy
   * @returns {import('spdy')}
   */
  onRequire(spdy) {
    patcher.patch(spdy, 'createServer', {
      name: `${this.id}.createServer`,
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      post: ({ args, result }) => {
        this.handleServerCreate(args, result);
      }
    });

    patcher.patch(spdy.response, 'push', {
      name: 'spdy.response.push',
      patchType: PATCH_TYPES.FRAMEWORK,
      pre(data) {
        agentEmitter.emit(
          HTTP_RESPONSE_HOOKED_METHOD_KEYS.PUSH,
          data.args[0],
          SINK_TYPES.RESPONSE_BODY
        );

        const body = data.args[0];
        if (isString(body)) {
          emitSendEvent(body.valueOf());
        }
      }
    });

    return spdy;
  }

  /**
   * Emits a create event for the new Server instance.
   * @param {any[]} args The arguments passed to the Server constructor
   * @param {import('net').Server} server The http Server instance
   */
  handleServerCreate(args, server) {
    super.handleServerCreate(args, server);

    patcher.patch(server, 'listen', {
      name: `${this.id}.SpdyFramework.listen`,
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      pre: ({ args, obj }) => this.handleServerListen(args, obj)
    });
  }
}

module.exports = SpdyFramework;
