//const Connections = require("../models/CreateConnections");
//const Tank = require("../models/tanks");
const { Tank, MotorData } = require('../models/tanks')


const User = require("../models/User");
const boom = require("boom");
const fastify = require("fastify")({
  logger: true,
});





exports.createConnections = async (req, res) => {
  try {
    const customerId = req.params.customerId;
    const tankname = req.body.tankname;
    const usertobeInserted = req.body;

    
    // Find the current tank
    const tankInfo = await Tank.findOne({
      customerId: customerId.toString(),
      tankName: tankname,
    });

    if (!tankInfo) throw new Error(`Tank ${tankname} not found`);

    // Update source of connections
    tankInfo.connections.source = tankInfo.tankName;

    // Map inputConnections if provided
    if (usertobeInserted.inputConnections) {
      tankInfo.connections.inputConnections = usertobeInserted.inputConnections.map(
        (connection) => ({
          inputConnections: connection.inputConnections,
          input_type: connection.input_type,
          motor_id: connection.motor_id || null,
          motor_status: connection.motor_status || "0",
          motor_stop_status: connection.motor_stop_status || "1",
          inputismotor: connection.hasOwnProperty("inputismotor")
            ? connection.inputismotor
            : false,
          capacity: connection.capacity || null,
          water_level: connection.water_level || null,
        })
      );
    }

    // Map outputConnections if provided
    if (usertobeInserted.outputConnections) {
      tankInfo.connections.outputConnections = usertobeInserted.outputConnections.map(
        (connection) => ({
          outputConnections: connection.outputConnections,
          output_type: connection.output_type,
          motor_id: connection.motor_id || null,
          motor_status: connection.motor_status || "0",
          motor_stop_status: connection.motor_stop_status || "1",
          outputismotor: connection.hasOwnProperty("outputismotor")
            ? connection.outputismotor
            : false,
          capacity: connection.capacity || null,
          water_level: connection.water_level || null,
        })
      );
    }

    // Save the updated tank
    const tankConnections = await tankInfo.save();

    // Handle input-to-output and output-to-input logic
    const { inputConnections = [], outputConnections = [] } = usertobeInserted;

    // Process inputConnections
    for (const input of inputConnections) {
      const relatedTankName = input.inputConnections;

      // Ensure the related tank exists
      const relatedTank = await Tank.findOne({
        customerId: customerId.toString(),
        tankName: relatedTankName,
      });

      if (relatedTank) {
        // Check if the current tank already exists in the related tank's outputConnections
        const existsInOutput = relatedTank.connections.outputConnections.some(
          (conn) => conn.outputConnections === tankname
        );

        if (!existsInOutput) {
          relatedTank.connections.outputConnections.push({
            outputConnections: tankname,
            output_type: "sump",
            motor_id: input.motor_id || null,
            motor_status: input.motor_status || "0",
            motor_stop_status: input.motor_stop_status || "1",
            outputismotor: input.inputismotor || false,
            capacity: tankInfo.capacity || null,
            water_level: tankInfo.waterlevel || null,
          });

          await relatedTank.save();
        }
      }
    }

    // Process outputConnections
    for (const output of outputConnections) {
      const relatedTankName = output.outputConnections;

      // Ensure the related tank exists
      const relatedTank = await Tank.findOne({
        customerId: customerId.toString(),
        tankName: relatedTankName,
      });

      if (relatedTank) {
        // Check if the current tank already exists in the related tank's inputConnections
        const existsInInput = relatedTank.connections.inputConnections.some(
          (conn) => conn.inputConnections === tankname
        );

        if (!existsInInput) {
          relatedTank.connections.inputConnections.push({
            inputConnections: tankname,
            input_type: "overhead",
            motor_id: output.motor_id || null,
            motor_status: output.motor_status || "0",
            motor_stop_status: output.motor_stop_status || "1",
            inputismotor: output.outputismotor || false,
            capacity: tankInfo.capacity || null,
            water_level: tankInfo.waterlevel || null,
          });

          await relatedTank.save();
        }
      }
    }

    return res.send({ success: true, data: tankConnections });
  } catch (err) {
    console.error(err);
    throw boom.boomify(err);
  }
};

  






exports.updateconnectionInfo = async (req, reply) => {
  try {
    //const username = loginObject.user.username;
    const tankname = req.body.tankname
    const customerId = req.params.customerId;
    const tankInfo = await Tank.findOne({ customerId: customerId.toString(),tankName:tankname  })
    const updateData = req.body;
    
    tankInfo.connections.source = tankInfo.tankName;
    // if (updateData.inputConnections) tankInfo.connections.inputConnections = updateData.inputConnections;
    // if (updateData.outputConnections) tankInfo.connections.outputConnections = updateData.outputConnections;    
    // Update the tank's input connections if provided
    if (updateData.inputConnections) {
      tankInfo.connections.inputConnections = updateData.inputConnections.map(connection => {
          return {
              inputConnections: connection.inputConnections,
              input_type: connection.input_type,
              motor_status: connection.motor_status || "0",
              inputismotor: connection.inputismotor || false // default to false if not specified
          };
      });
    }

    // Update the tank's output connections if provided
    if (updateData.outputConnections) {
      tankInfo.connections.outputConnections = updateData.outputConnections.map(connection => {
          return {
              outputConnections: connection.outputConnections,
              output_type: connection.output_type,
              outputismotor: connection.outputismotor || false // default to false if not specified
          };
      });
    }

    const tank_connections = await tankInfo.save();
    return tank_connections;
  } catch (err) {
    throw boom.boomify(err);
  }
};

exports.getConnections = async (req, reply) => {
  try {
    var connectionsData=await Tank.find({customerId: req.query.customerId})
   // var connection_data = connectionsData.connections
      
      reply.send({ status_code: 200, data: connectionsData});
     // return tank;
  
  
      // return tank;
     } catch (err) {
       throw boom.boomify(err);
     }
   };


   exports.deleteTankConnections = async (req, reply) => {
    try {
      const customerId = req.params.customerId;
      const tankname  = req.query.tankName;
      
      const tankInfo = await Tank.findOne({ customerId: customerId.toString(),tankName:tankname })
      console.log(tankInfo)
      
      tankInfo.connections.source = tankInfo.tankName;
      tankInfo.connections.inputConnections = [];
      tankInfo.connections.outputConnections = [];    
      const tank_connections = await tankInfo.save();
      return tank_connections;
    } catch (err) {
      throw boom.boomify(err);
    }
  };


  
  
   

