const mongoose = require("mongoose");
const moment = require('moment');



const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;

// Store a random password reset code
const code = Math.floor(100000 + Math.random() * 900000);
const RoleSchema = new Schema({ name: String });
// const tanksSchema = new mongoose.Schema({
//     hardwareId: { type: String },
//     hardwareId_type: { type: String },
//     hardwareId_company: { type: String },
//     customerId: { type: String, default: null },
//     tankName: { type: String, default: null },
//     blockName: { type: String, default: null },
//     capacity: { type: String, default: "0" },
//     typeOfWater: { type: String, default: null },
//     waterlevel: { type: String, default: "0" },
//     tankLocation: { type: String, default: null },
//     motor_status: { type: String, default: 0 },
//     connections: {
//         source: { type: String},
//         inputConnections: [{ inputConnections: String,input_type:String,motor_status: { type: String, default: "0" } }],
//         outputConnections: [{ outputConnections: String,output_type:String }]
//     }


// });


const tanksSchema = new mongoose.Schema({
  hardwareId: { type: String },
  InstallerId: { type: String, default: null },
  tankhardwareId: { type: String },
  hardwareId_type: { type: String },
  hardwareId_company: { type: String },
  customerId: { type: String, default: null },
  tankName: { type: String, default: null },
  blockName: { type: String, default: null },
  shape: { type: String, default: null },
  capacity: { type: String, default: "0" },
  height: { type: String, default: "0" },
  length: { type: String, default: "0" },
  width: { type: String, default: "0" },
  tankLocation: { type: String, default: null },
  waterCapacityPerCm: { type: String, default: "0" },
  typeOfWater: { type: String, default: null },
  waterlevel: { type: String, default: "0" },
  waterlevel_at_midnight: { type: String, default: "0" },
  need_sensor:{ type: String, default: "no" },
  total_water_added_from_midnight: { type: String, default: "0" },
  auto_min_percentage: { type: String, default: "20" },
  reserved_percentage: { type: String, default: "20" },
  auto_max_percentage: { type: String, default: "80" },
  auto_mode_type: { type: String, default: "default" },
  notificationSentCritical: { type: Boolean },
  notificationSentVeryLow: { type: Boolean },
  notificationSentLow: { type: Boolean },
  notificationSentCriticalHigh: { type: Boolean },
  notificationSentVeryHigh: { type: Boolean },
  notificationSentHigh: { type: Boolean },
  all_motor_status: { type: Boolean },
  status:{ type: String, default: "active" },
  slave_status:{ type: String, default: "working" },
  slave_disconnected_time   :{ type: String, default: null },
  
  connections: {
    source: { type: String },
    inputConnections: [
      {
        inputConnections: { type: String },
        input_type: { type: String },
        inputismotor: { type: Boolean },
        motor_id: { type: String, default: null },
        motor_status: { type: String, default: "0" },
        auto_mode: { type: String, default: "inactive" },
        motor_stop_status: { type: String, default: "1" },
        motor_on_type: { type: String, default: "manual" },
        capacity: { type: String, default: null },
        water_level: { type: String, default: null },
        manual_threshold_percentage: { type: String, default: "90" },
        manual_threshold_time: { type: String, default: null },
        status:{ type: String, default: "active" },
        stop_threshold_time: { type: String, default: null },
        threshold_type: { type: String, default: "percentage" },
        startTime: { type: String, default: null },
        start_instance_id: { type: String, default: null },
        stopTime: { type: String, default: null },
        waterlevelPercentage: { type: String, default: null } ,
        slave_status:{ type: String, default: "working" },
      }
    ],
    outputConnections: [
      {
        outputConnections: { type: String },
        output_type: { type: String },
        outputismotor: { type: Boolean },
        motor_id: { type: String, default: null },
        motor_status: { type: String, default: "0" },
        motor_stop_status: { type: String, default: "1" },
        capacity: { type: String, default: null },
        water_level: { type: String, default: null },
        manual_threshold_percentage: { type: String, default: "90" },
        manual_threshold_time: { type: String, default: null },
        threshold_type: { type: String, default: "percentage" },
        waterlevelPercentage: { type: String, default: null } ,
        status:{ type: String, default: "active" },
      }
    ],
    inputWaterlevelPercentage: { type: String, default: null }, 
    outputWaterlevelPercentage: { type: String, default: null } 
  },
  motor_start_notified: { type: Boolean, default: false },
  motor_stop_notified: { type: Boolean, default: false }

});

const customerautopercentages = ({
  customerId: { type: String },
  auto_min_percentage: { type: String, required: true },
  auto_max_percentage: { type: String,default:null },

  date: { type: String, required: true },
 
});


const motordataSchema = new mongoose.Schema({
    customerId: { type: String, default: null },
    motor_id: { type: String, default: null },
    started_by:{ type: String, default: "user" },
    start_instance_id:{type:String,default:null},
    supplierTank: { type: String, default: null },
    receiverTank: { type: String, default: null },
    supplierInitialwaterlevel: { type: String, default: "0" },
    supplierfinalwaterlevel: { type: String, default: "0" },
    startTime:   { type: String, default: null },
    stopTime:   { type: String, default: null },
    runtime:{type:String, default:"0"},
    supplier_type: { type: String, default: null },
    receiver_type: { type: String, default: null },
    quantity_delivered:{ type: String, default: null },
    receiverInitialwaterlevel: { type: String, default: "0" },
    receiverfinalwaterlevel: { type: String, default: "0" },
    started_by: { type: String, default: "user" },
    stopped_by: { type: String, default: "user" }
});


const updateMotorData = async () => {
  try {
    // Fetch all motor data where quantity_delivered is null or needs updating
    const motorDataRecords = await MotorData.find({});

    for (let record of motorDataRecords) {
      // Convert string values to numbers by removing commas
      const initialLevel = parseInt(record.receiverInitialwaterlevel.replace(/,/g, ""), 10) || 0;
      const finalLevel = parseInt(record.receiverfinalwaterlevel.replace(/,/g, ""), 10) || 0;

      // Calculate quantity delivered
      const quantityDelivered = finalLevel - initialLevel;

      // Update the record
      await MotorData.updateOne(
        { _id: record._id },
        {
          $set: {
            started_by: "user",
            quantity_delivered: quantityDelivered.toString(), // Convert back to string for consistency
          },
        }
      );
    }

    console.log("Motor data updated successfully!");
  } catch (err) {
    console.error("Error updating motor data:", err);
  }
};

const tankSchema = new mongoose.Schema({
  tankhardwareId: { type: String },
  tankHeight: { type: String, required: true },
  maxLevel: { type: String,default:null },
  minLevel: { type: String,default:null },
  date: { type: String, required: true },
  time: { type: String, required: true }
});

const IOttankSchema = new mongoose.Schema({
  hardwareId: { type: String },
  mode: { type: String },
  tanks: [tankSchema],
  date: { type: String, required: true },
  time: { type: String, required: true }
});


const tankWaterLevelSchema = new mongoose.Schema({
  customerId: { type: String },
  tankName: { type: String },
  tankLocation: { type: String },
  waterlevel: { type: String },
  time: { type: String }
});

const tankconsumptionSchema = new mongoose.Schema({
  customerId: { type: String },
  tankName: { type: String },
  tankLocation: { type: String },
  consumption: { type: String },
  block:{type: String},
  typeofwater:{type:String},
  time: { type: String }
});


const tankconsumptionoriginalSchema = new mongoose.Schema({
  customerId: { type: String },
  tankName: { type: String },
  tankLocation: { type: String },
  consumption: { type: String },
  consumed_percentage:{ type: String },
  available_capacity:{ type: String },
  block:{type: String},
  typeofwater:{type:String},
  time: { type: String }
});
 

const Tank = mongoose.model("Tank", tanksSchema);
const CustomerAutoPercentages = mongoose.model("CustomerAutoPercentages", customerautopercentages);

const MotorData = mongoose.model("MotorData", motordataSchema);
const TankWaterLevel = mongoose.model("TankWaterLevel", tankWaterLevelSchema);
const IotData = mongoose.model("IotData", IOttankSchema);
const TankConsumptionSchema = mongoose.model("TankConsumptionSchema", tankconsumptionSchema);
const TankConsumptionOriginalSchema = mongoose.model("TankConsumptionOriginalSchema", tankconsumptionoriginalSchema);


module.exports = {
    Tank, MotorData,IotData,TankWaterLevel,TankConsumptionSchema,TankConsumptionOriginalSchema,CustomerAutoPercentages
}

