/**
 * measurement.class.js
 *
 * Encapsulates all node logic in a reusable class. In future updates we can split this into multiple generic classes and use the config to specifiy which ones to use.
 * This allows us to keep the Node-RED node clean and focused on wiring up the UI and event handlers.
 */
const { outputUtils, configManager } = require('generalFunctions');
const Specific = require("./specificClass");


class nodeClass {
  /**
   * Create a MeasurementNode.
   * @param {object} uiConfig - Node-RED node configuration.
   * @param {object} RED    - Node-RED runtime API.
   * @param {object} nodeInstance - The Node-RED node instance.
   * @param {string} nameOfNode - The name of the node, used for
   */
  constructor(uiConfig, RED, nodeInstance, nameOfNode) {

    // Preserve RED reference for HTTP endpoints if needed
    this.node = nodeInstance;
    this.RED = RED;
    this.name = nameOfNode;

    // Load default & UI config
    this._loadConfig(uiConfig,this.node);

    // Instantiate core Measurement class
    this._setupSpecificClass();

    // Wire up event and lifecycle handlers
    this._bindEvents();
    this._registerChild();
    this._startTickLoop();
    this._attachInputHandler();
    this._attachCloseHandler();
  }

  /**
   * Load and merge default config with user-defined settings.
   * @param {object} uiConfig - Raw config from Node-RED UI.
   */
  _loadConfig(uiConfig,node) {
    const cfgMgr = new configManager();
    this.defaultConfig = cfgMgr.getConfig(this.name);

    // Merge UI config over defaults
    this.config = {
      general: {
        name: this.name,
        id: node.id, // node.id is for the child registration process
        unit: uiConfig.unit, // add converter options later to convert to default units (need like a model that defines this which units we are going to use and then conver to those standards)
        logging: {
          enabled: uiConfig.enableLog,
          logLevel: uiConfig.logLevel
        }
      },
      asset: {
        uuid: uiConfig.assetUuid, //need to add this later to the asset model
        tagCode: uiConfig.assetTagCode, //need to add this later to the asset model
        tagNumber: uiConfig.assetTagNumber,
        supplier: uiConfig.supplier,
        category: uiConfig.category, //add later to define as the software type 
        type: uiConfig.assetType,
        model: uiConfig.model,
        unit: uiConfig.unit
      },
      scaling: {
        enabled: uiConfig.scaling,
        inputMin: uiConfig.i_min,
        inputMax: uiConfig.i_max,
        absMin: uiConfig.o_min,
        absMax: uiConfig.o_max,
        offset: uiConfig.i_offset
      },
      smoothing: {
        smoothWindow: uiConfig.count,
        smoothMethod: uiConfig.smooth_method
      },
      simulation: {
        enabled: uiConfig.simulator
      },
      functionality: {
        positionVsParent: uiConfig.positionVsParent,// Default to 'atEquipment' if not specified
        distance: uiConfig.hasDistance ? uiConfig.distance : undefined
      }
    };

    console.log(`position vs child for ${this.name} is ${this.config.functionality.positionVsParent} the distance is ${this.config.functionality.distance}`);

    // Utility for formatting outputs
    this._output = new outputUtils();
  }

  /**
   * Instantiate the core logic and store as source.
   */
  _setupSpecificClass() {
    this.source = new Specific(this.config);
    this.node.source = this.source; // Store the source in the node instance for easy access
  }

  /**
   * Bind Measurement events to Node-RED status updates. Using internal emitter. --> REMOVE LATER WE NEED ONLY COMPLETE CHILDS AND THEN CHECK FOR UPDATES
   */
  _bindEvents() {

    this.source.emitter.on('mAbs', (val) => {
      this.node.status({ fill: 'green', shape: 'dot', text: `${val} ${this.config.general.unit}` });
    });
    
  }

  /**
   * Register this node as a child upstream and downstream.
   * Delayed to avoid Node-RED startup race conditions.
   */
  _registerChild() {
    setTimeout(() => {
      this.node.send([
        null,
        null,
        { topic: 'registerChild', payload: this.node.id , positionVsParent: this.config?.functionality?.positionVsParent || 'atEquipment' , distance: this.config?.functionality?.distance || null},
      ]);
    }, 100);
  }

  /**
   * Start the periodic tick loop to drive the Measurement class.
   */
  _startTickLoop() {
    setTimeout(() => {
      this._tickInterval = setInterval(() => this._tick(), 1000);
    }, 1000);
  }

  /**
   * Execute a single tick: update measurement, format and send outputs.
   */
  _tick() {
    this.source.tick();

    const raw = this.source.getOutput();
    const processMsg = this._output.formatMsg(raw, this.config, 'process');
    const influxMsg  = this._output.formatMsg(raw, this.config, 'influxdb');

    // Send only updated outputs on ports 0 & 1
    this.node.send([processMsg, influxMsg]);
  }

  /**
   * Attach the node's input handler, routing control messages to the class.
   */
  _attachInputHandler() {
    this.node.on('input', (msg, send, done) => {
      switch (msg.topic) {
        case 'simulator':           this.source.toggleSimulation();      break;
        case 'outlierDetection':    this.source.toggleOutlierDetection(); break;
        case 'calibrate':           this.source.calibrate();             break;
        case 'measurement':
          if (typeof msg.payload === 'number') {
            this.source.inputValue = parseFloat(msg.payload);
          }
          break;
      }
      done();
    });
  }

  /**
   * Clean up timers and intervals when Node-RED stops the node.
   */
  _attachCloseHandler() {
    this.node.on('close', (done) => {
      clearInterval(this._tickInterval);
      //clearInterval(this._statusInterval);
      done();
    });
  }
}

module.exports = nodeClass;
