/**
 * node 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, convert } = require('generalFunctions');
const Specific = require("./specificClass");

class nodeClass {
  /**
   * Create a Node.
   * @param {object} uiConfig - Node-RED node configuration.
   * @param {object} RED    - Node-RED runtime API.
   */
  constructor(uiConfig, RED, nodeInstance, nameOfNode) {

    // Preserve RED reference for HTTP endpoints if needed
    this.node = nodeInstance; // This is the Node-RED node instance, we can use this to send messages and update status
    this.RED = RED; // This is the Node-RED runtime API, we can use this to create endpoints if needed
    this.name = nameOfNode; // This is the name of the node, it should match the file name and the node type in Node-RED
    this.source = null; // Will hold the specific class instance
    this.config = null; // Will hold the merged configuration

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

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

    // 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: uiConfig.name || uiConfig.category || 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.uuid,
        tagCode: uiConfig.assetTagCode,
        supplier: uiConfig.supplier,
        category: uiConfig.category, //add later to define as the software type 
        type: uiConfig.assetType,
        model: uiConfig.model,
        unit: uiConfig.unit,
        emptyWeightBucket: Number(uiConfig.emptyWeightBucket)
      },
      constraints: {
        samplingtime: Number(uiConfig.samplingtime),
        minVolume: Number(uiConfig.minvolume),
        maxWeight: Number(uiConfig.maxweight),
        nominalFlowMin: Number(uiConfig.nominalFlowMin),
        flowMax: Number(uiConfig.flowMax),
        maxRainRef: Number(uiConfig.maxRainRef),
        minSampleIntervalSec: Number(uiConfig.minSampleIntervalSec),
      },
      functionality: {
        positionVsParent: uiConfig.positionVsParent || 'atEquipment',
        distance: uiConfig.hasDistance ? uiConfig.distance : undefined
      }
    };

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

  /**
   * Instantiate the core Measurement logic and store as source.
   */
  _setupSpecificClass(uiConfig) {
    const monsterConfig = this.config;

    this.source = new Specific(monsterConfig);

    if (uiConfig?.aquon_sample_name) {
      this.source.aquonSampleName = uiConfig.aquon_sample_name;
    }

    //store in node 
    this.node.source = this.source; // Store the source in the node instance for easy access
  
  }

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

  }

  _updateNodeStatus() {
    const m = this.source;
try{
          const bucketVol = m.bucketVol;
          const maxVolume = m.maxVolume;
          const state = m.running;
          const mode = "AI"; //m.mode;
          const flowMin = m.nominalFlowMin;
          const flowMax = m.flowMax;

          if (m.invalidFlowBounds) {
            return {
              fill: "red",
              shape: "ring",
              text: `Config error: nominalFlowMin (${flowMin}) >= flowMax (${flowMax})`
            };
          }

          if (state) {
            const levelText = `${bucketVol}/${maxVolume} L`;
            const cooldownMs = typeof m.getSampleCooldownMs === 'function'
              ? m.getSampleCooldownMs()
              : 0;

            if (cooldownMs > 0) {
              const cooldownSec = Math.ceil(cooldownMs / 1000);
              return { fill: "yellow", shape: "ring", text: `SAMPLING (${cooldownSec}s) ${levelText}` };
            }

            return { fill: "green", shape: "dot", text: `${mode}: RUNNING ${levelText}` };
          }

          return { fill: "grey", shape: "ring", text: `${mode}: IDLE` };
      } catch (error) {
        this.node.error("Error in updateNodeStatus: " + error);
        return { fill: "red", shape: "ring", text: "Status Error" };
      }
    }
  /**
   * 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.config.general.id, positionVsParent: this.config?.functionality?.positionVsParent || 'atEquipment' },
      ]);
    }, 100);
  }

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

      // Update node status on nodered screen every second ( this is not the best way to do this, but it works for now)
      this._statusInterval = setInterval(() => {
        const status = this._updateNodeStatus();
        this.node.status(status);
      }, 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) => {
     /* Update to complete event based node by putting the tick function after an input event */
      const m = this.source;
      try {
        switch(msg.topic) {
          case 'input_q': {
            const value = Number(msg.payload?.value);
            const unit = msg.payload?.unit;
            if (!Number.isFinite(value) || !unit) {
              this.node.warn('input_q payload must include numeric value and unit.');
              break;
            }
            let converted = value;
            try {
              converted = convert(value).from(unit).to('m3/h');
            } catch (error) {
              this.node.warn(`input_q unit conversion failed: ${error.message}`);
              break;
            }
            m.handleInput('input_q', { value: converted, unit: 'm3/h' });
            break;
          }
          case 'i_start':
          case 'monsternametijden':
          case 'rain_data':
            m.handleInput(msg.topic, msg.payload);
            break;
          case 'registerChild': {
            const childId = msg.payload;
            const childObj = this.RED.nodes.getNode(childId);
            if (childObj?.source) {
              m.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
            }
            break;
          }
          case 'setMode':
            m.setMode(msg.payload);
            break;
          case 'execSequence': {
            const { source, action, parameter } = msg.payload || {};
            m.handleInput(source, action, parameter);
            break;
          }
          case 'execMovement': {
            const { source: mvSource, action: mvAction, setpoint } = msg.payload || {};
            m.handleInput(mvSource, mvAction, Number(setpoint));
            break;
          }
          case 'flowMovement': {
            const { source: fmSource, action: fmAction, setpoint: fmSetpoint } = msg.payload || {};
            m.handleInput(fmSource, fmAction, Number(fmSetpoint));
            break;
          }
          case 'emergencystop': {
            const { source: esSource, action: esAction } = msg.payload || {};
            m.handleInput(esSource, esAction);
            break;
          }
          case 'showWorkingCurves':
            send({ topic : "Showing curve" , payload: m.showWorkingCurves() });
            break;
          case 'CoG':
            send({ topic : "Showing CoG" , payload: m.showCoG() });
            break;
          default:
            break;
        }
      } catch (error) {
        this.node.error(`Error handling input (${msg?.topic}): ${error?.message || error}`);
      } finally {
        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;
