// console.log("load gaugesScreen");
angular.module('gaugesScreen', [])

  .controller('GaugesScreenController', function ($scope, $element, $window) {
    "use strict";
    var vm = this;

    var speedoDisplay = { };
    var infoDisplay = {};
    var gagues = {fuel:[]};

    var speedoInitialised = true;

    var ready = false;

    var unitspeedConv = 3.6;
    var unitLen = "metric";

    $scope.onLoaded = function () {
      speedoDisplay = document.getElementById('speedo');
      infoDisplay.odo = document.getElementById('odo');
      infoDisplay.odo.innerHTML = "0";

      for (let i = 1; i < 8; i++) {
        gagues.fuel.push(document.getElementById('fuel'+i))
      }

      ready = true;
      //console.log("rdy")
    }

    function limitVal(min, val,max){
        return Math.min(Math.max(min,val), max);
    }

    function updateGagueFuel(data) {
      if (speedoInitialised) {
        for (let i = 0; i < gagues.fuel.length; i++) {
          gagues.fuel[i].style.display = (i+0.5 < data["electrics"]["fuel"]*gagues.fuel.length)?"inline":"none";
        }
      }
    }

    // overwriting plain javascript function so we can access from within the controller
    $window.setup = (data) => {
      if(!ready){
        console.log("calling setup while svg not fully loaded");
        setTimeout(function(){ $window.setup(data) }, 100);
        return;
      }

      //console.log("setup",data);
      if(data.uiUnitLength == "metric"){
        unitspeedConv = 3.6;
      }
      else{
        unitspeedConv = 2.23694;
      }
      unitLen = data.uiUnitLength
    }

    $window.updateData = (data) => {
      if (data) {
        if(!ready){console.log("not ready");return;}
        // console.log(data);
        // Update Speed displays
        speedoDisplay.innerHTML =  limitVal(0,data.electrics.wheelspeed * unitspeedConv,199).toFixed();

        updateGagueFuel(data);
        if(data.electrics.odometer){
          let val = data.electrics.odometer
          val *= (unitLen=="metric")?0.001:0.0006215;
          val = Math.min(val,99999)
          infoDisplay.odo.innerHTML = val.toFixed(0)
        }
      }
    }
    //ready = true;
    $scope.onLoaded();
  });