{"size": 1605, "ext": "js", "max_stars_repo_path": "nodes/quantum/reset/reset.js", "max_stars_repo_name": "SheaMagennis/Quantum-Security-Gateway", "max_stars_repo_stars_event_min_datetime": "2021-06-16T12:43:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T06:57:06.000Z", "max_issues_repo_path": "nodes/quantum/reset/reset.js", "max_issues_repo_name": "SheaMagennis/Quantum-Security-Gateway", "max_issues_repo_issues_event_min_datetime": "2021-07-05T23:59:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T15:24:26.000Z", "max_forks_repo_path": "nodes/quantum/reset/reset.js", "max_forks_repo_name": "SheaMagennis/Quantum-Security-Gateway", "max_forks_repo_forks_event_min_datetime": "2021-07-12T09:32:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T09:32:10.000Z"}
{"max_stars_count": 4, "max_issues_count": 54, "max_forks_count": 1, "avg_line_length": 30.2830188679, "max_line_length": 103, "alphanum_fraction": 0.5763239875}
'use strict';

const util = require('util');
const snippets = require('../../snippets');
const shell = require('../../python').PythonShell;
const errors = require('../../errors');
const logger = require('../../logger');

module.exports = function(RED) {
  function ResetNode(config) {
    RED.nodes.createNode(this, config);
    this.name = config.name;
    const node = this;

    logger.trace(this.id, 'Initialised reset');

    this.on('input', async function(msg, send, done) {
      logger.trace(node.id, 'Reset received input');
      let script = '';

      // Validate the node input msg: check for qubit object.
      // Return corresponding errors or null if no errors.
      // Stop the node execution upon an error
      let error = errors.validateQubitInput(msg);
      if (error) {
        logger.error(node.id, error);
        done(error);
        return;
      }

      if (typeof msg.payload.register === 'undefined') {
        script += util.format(snippets.RESET, msg.payload.qubit);
      } else {
        script += util.format(snippets.RESET, msg.payload.registerVar + '[' + msg.payload.qubit + ']');
      }

      // Run the script in the python shell, and if no error occurs
      // then send msg object to the next node
      await shell.execute(script)
          .then(() => {
            send(msg);
            done();
          }).catch((err) => {
            logger.error(node.id, err);
            done(err);
          }).finally(() => {
            logger.trace(node.id, 'Executed reset command');
          });
    });
  }
  RED.nodes.registerType('reset', ResetNode);
};
