/**
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 BaseConnectionState = require('./base-connection-state');
const {
  CONNECTION_STATES: { SUCCESS, UNKNOWN }
} = require('./constants');

/**
 * Localizes state-specific behavior related to sending messages to the
 * contrast-service while the Speedracer instance is in the SUCCESS connection
 * state i.e. sending/recieving message successfully.
 * From within this state, valid state transitions are either FAILURE or UNKNOWN.
 */
class SuccessConnectionState extends BaseConnectionState {
  constructor(speedracer) {
    super(speedracer);
    this.state = SUCCESS;
  }

  /**
   * Sends a message to the service.
   * @param {SpeedracerBaseMessage} message
   * @returns {Promise}
   */
  send(message) {
    const { speedracer } = this;
    let clientResponse;

    return new Promise(async (resolve, reject) => {
      try {
        // why super.send() but if catch(err) speedracer.send()? is BaseConnectionState.send()
        // which executes speedracer.connectionState.send(),
        clientResponse = await super.send(message);
        resolve(clientResponse);
      } catch (err) {
        if (speedracer.client.isConnectFailureError(err)) {
          speedracer.transitionConnectionState(UNKNOWN);
          try {
            // speedracer.send() is connectionState.send()
            clientResponse = await speedracer.send(message);
            resolve(clientResponse);
          } catch (err) {
            reject(err);
          }
        } else {
          reject(err);
        }
      }
    });
  }
}

module.exports = SuccessConnectionState;
