angular.module('gaugesScreen', [])
.controller('GaugesScreenController', function($scope, $window) {

	  const rpmMax = 7000;
  const speedMax = 330;
  const tempMax = 130;
  const fuelMax = 100;
  const oilTempMax = 150;
  
  
  var units = {uiUnitConsumptionRate: "metric",
  uiUnitDate: "ger",
  uiUnitEnergy: "metric",
  uiUnitLength: "metric",
  uiUnitPower: "hp",
  uiUnitPressure: "bar",
  uiUnitTemperature: "c",
  uiUnitTorque: "metric",
  uiUnitVolume: "l",
  uiUnitWeight: "kg"};
  
  $scope.data = {};

  let lastRpm = 0, targetRpm = 0;
  let lastSpeed = 0, targetSpeed = 0;
  let lastTemp = 0, targetTemp = 0;
  let lastFuel = 0, targetFuel = 0;
  let lastOil = 0, targetOil = 0;
  let lastFuelCons = 0, targetFuelCons = 0;




  $window.setup = (setupData) => {
    for(let dk in setupData){
      if(typeof dk == "string" && dk.startsWith("uiUnit")){
        units[dk] = setupData[dk];
      }
    }
    vueEventBus.emit('SettingsChanged', {values:units})

    $scope.data.speedUnit = units.uiUnitLength=="metric"?"km/h":"mph";
  };

  $window.updateData = (data) => {
    $scope.$evalAsync(() => {

      const rpm = data.electrics.rpm || 0;
      const speed = UiUnits.speed(data.electrics.wheelspeed).val.toFixed(0);
      const fuel = data.electrics.fuel || 0;
      const coolant = data.electrics.watertemp || 0; 
	  const odometer  = Math.round(data.electrics?.nsx_gu_odometer || 0);
      const oiltemp = data.electrics.oiltemp || 0;
      const time = data.customModules?.environmentData?.time || "--:--";
      const currentFuelConsumption = data.customModules?.combustionEngineData?.currentFuelConsumption || 0;

      targetRpm = rpm;
      targetSpeed = speed;
      targetFuel = fuel * 100;
      targetTemp = coolant;
      targetOil = oiltemp;
      targetFuelCons = currentFuelConsumption;


      $scope.data.engineRpm = Math.round(rpm);

	 
      $scope.data.speedUnit = (units.uiUnitLength === "metric") ? "km/h" : "mph";
      $scope.data.engineRpm = Math.round(rpm);
      $scope.data.fuel = Math.round(fuel * 100);
      $scope.data.speedVal = Math.round(speed);
      $scope.data.time = time;
	  
	 
	

	  
if (typeof data.electrics.nsx_gu_odometer === "number") {
  let valKm = Math.round(data.electrics.nsx_gu_odometer);
  valKm = Math.min(999999, Math.max(0, valKm));
  $scope.data.odo = valKm.toString().padStart(6, "0") + (units.uiUnitLength === "metric" ? " km" : " mi");
  
  
} else {
  $scope.data.odo = "000000";
}

      $scope.data.fuelConsumption = (units.uiUnitLength === "metric")
        ? currentFuelConsumption.toFixed(1) + " l/100km"
        : (235.2 / currentFuelConsumption).toFixed(1) + " mpg";


let temperatureEnv = data.customModules?.environmentData?.temperatureEnv;
if (units.uiUnitTemperature === 'c') {
  $scope.data.temp = (temperatureEnv > 99.9 || temperatureEnv < -99.9)
    ? "---°C"
    : temperatureEnv.toFixed(0) + " °C";
} else {
  const fahrenheit = (temperatureEnv * 9 / 5) + 32;
  $scope.data.temp = (fahrenheit > 99.9 || fahrenheit < -99.9)
    ? "---°F"
    : fahrenheit.toFixed(0) + " °F";
}


let rawGear = data.electrics.gear;

if (rawGear === -1) {
  $scope.data.gear = "R";
} else if (rawGear === 0) {
  $scope.data.gear = "N";
} else if (typeof rawGear === "string") {
  if (rawGear.startsWith("S")) {
    $scope.data.gear = "S";
  } else if (rawGear.startsWith("M")) {
    $scope.data.gear = "M";
  } else if (rawGear.startsWith("D")) {
    $scope.data.gear = "D";
  } else {
    $scope.data.gear = rawGear;
  }
} else {
  $scope.data.gear = rawGear;
}


const fuelUsed = data.engine?.fuelUsed || 0;
const distanceKm = odometer / 1000;
let avgConsumption = 15;
if (distanceKm > 0.5 && fuelUsed > 0.01) {
  avgConsumption = (fuelUsed / distanceKm) * 100;
}
const fuelCapacity = data.engine?.fuelCapacity || 90;
const fuelLiters = fuel * fuelCapacity;
let range = (fuelLiters / avgConsumption) * 100;

if (units.uiUnitLength !== "metric") {
  range *= 0.621371; // km -> mi
}

$scope.data.range = Math.round(range) + (units.uiUnitLength === "metric" ? " km" : " mi");


    });
  };
});
