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

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

    var svg;
    var navContainer = $element[0].children[0];
    var navDimensions = [];
    var downD = {};
    var dd2 = { ggrr: {} };
    var second = {};
    var first = {};
    var speedoDisplay = { gears: {} };
    var tacho = {  };
    var infoDisplay = {};
    var electrics = {lights:{} };
    var speedoInitialised = true;
    var cachedAng = {speedo:-100, tacho:-100, temp:-100, fuel:-100};
    var refreshAng = 0.25*Math.PI/180;
    var ready = false;
    var units = {uiUnitConsumptionRate: "metric",
    uiUnitDate: "ger",
    uiUnitEnergy: "metric",
    uiUnitLength: "metric",
    uiUnitPower: "hp",
    uiUnitPressure: "bar",
    uiUnitTemperature: "c",
    uiUnitTorque: "metric",
    uiUnitVolume: "l",
    uiUnitWeight: "kg"};
    var unit = "metric";
    var currentGear = '';
    var currentGearG = '';
    var unitspeedConv = 3.6;
    var unitspeedratio = 2.0*Math.PI*1.5/260;
    var rpmRatio = 0.1;
    var painduchocolat = {};
    $scope.onSVGLoaded = function () {
      svg = $element[0].children[0].children[0];
      painduchocolat.root = hu('#layer_wip', svg);
      painduchocolat.txt = hu('#wip.txt', painduchocolat.root);
      speedoDisplay.root = hu('#speedometer', svg);
      speedoDisplay.speedometerText = hu('#speedometerText', speedoDisplay.root)
      speedoDisplay.needle = hu('#needle', speedoDisplay.root);
      speedoDisplay.needle_bar = hu('#needle_bar', speedoDisplay.root);
      speedoDisplay.needle_gradients = [];
      speedoDisplay.needle_gradients.push(hu('#radialGradient965', svg));
      speedoDisplay.needle_lingradient = hu('#linearGradient1357', svg);
      speedoDisplay.needle_bar_highlight = hu('#needle_bar_highlight', speedoDisplay.root);
      speedoDisplay.needle_bar_highlightGrad = hu('#linearGradient1390', svg);
      speedoDisplay.gears.P = hu('#gearP', speedoDisplay.speedometerText);
      speedoDisplay.gears.R = hu('#gearR', speedoDisplay.speedometerText);
      speedoDisplay.gears.N = hu('#gearN', speedoDisplay.speedometerText);
      speedoDisplay.gears.D = hu('#gearD', speedoDisplay.speedometerText);
      speedoDisplay.gears.S = hu('#gearS', speedoDisplay.speedometerText);

      tacho.root = hu('#tacho', svg);
      tacho.gearindication = hu('#gearindication', tacho.root)
      tacho.bar = hu('#rpm_needle_bar', tacho.root);
      tacho.needle = hu('#rpm_needle', tacho.root);

      dd2.root = hu('#dd2', svg);
      dd2.groupg = hu('#groupg', dd2.root)
      dd2.tm2 = hu('#tm2', dd2.root);
      dd2.tmo2 = hu('#tmo2', dd2.root);
      dd2.speeds2d = hu('#speeds2d', dd2.root);
      dd2.ggrr.P = hu('#gearPD', dd2.groupg);
      dd2.ggrr.R = hu('#gearRD', dd2.groupg);
      dd2.ggrr.N = hu('#gearND', dd2.groupg);
      dd2.ggrr.D = hu('#gearDD', dd2.groupg);
      dd2.ggrr.S = hu('#gearSD', dd2.groupg);

      

      first.root = hu('#first', svg);
      second.root = hu('#second', svg);
      second.vert = hu('#vert', second.root);
      downD.root = hu('#downD', svg);
      downD.time = hu('#time', downD.root);
      downD.temp = hu('#temp', downD.root);
      downD.speeds = hu('#speeds', downD.root);



      tacho.needle_gradients = [];
      tacho.needle_gradients.push(hu('#radialGradient965-1', svg));
      tacho.needle_lingradient = hu('#linearGradient1369', svg);
      tacho.rpm_needle_bar_highlight  = hu('#rpm_needle_bar_highlight', tacho.root);
      tacho.rpm_needle_bar_highlightGrad = hu('#linearGradient1392', svg);
      ready = true;



    }

    function updateSpeedDisplays(data) {
      if (speedoInitialised) {
        var speedAng = 226 + ((data.electrics.wheelspeed * 2.35));
        var startAngle=-211*Math.PI/180, speedRad = (data.electrics.wheelspeed*0.7*Math.PI*2.5/260)+startAngle;
        var maxRad = (126*Math.PI/180) + startAngle;
        speedRad = Math.min(speedRad, maxRad);
        if(Math.abs(speedRad-cachedAng.speedo)<refreshAng){return;}
        cachedAng.speedo = speedRad;
        var centerX=95, centerY=31.5, radiusInt=15, radiusExt=110, largeArcFlag= ((speedRad-startAngle)>Math.PI)? 0 : 0, radiusExtH = radiusExt-1 ;
        var sx2 = (centerX) + Math.cos(startAngle) * radiusInt;
        var sy2 = (centerY) + Math.sin(startAngle) * radiusInt;

        var sx1 = (centerX) + Math.cos(startAngle) * radiusExt;
        var sy1 = (centerY) + Math.sin(startAngle) * radiusExt;

        var ex2 = (centerX) + Math.cos(speedRad) * radiusExt;
        var ey2 = (centerY) + Math.sin(speedRad) * radiusExt;

        var ex1 = (centerX);
        var ey1 = (centerY);

        var mx1 = (centerX) + Math.cos(speedRad) * 0;
        var my1 = (centerY) + Math.sin(speedRad) * 0;

        speedoDisplay.needle_bar.attr({d: "M " + sx1 + "," + sy1 +
          " A" + radiusExt  + "," + radiusExt  + " 0 "+largeArcFlag+",1 " + ex2 + "," + ey2 +
          " L " + ex1 + "," + ey1});
        speedoDisplay.needle.attr({d: "M " + ex1 + "," + ey1 + " " +ex2+","+ey2});

        ex2 = (centerX) + Math.cos(speedRad) * radiusExtH;
        ey2 = (centerY) + Math.sin(speedRad) * radiusExtH;
        ex1 = (centerX) + Math.cos(startAngle) * radiusExtH;
        ey1 = (centerY) + Math.sin(startAngle) * radiusExtH;
        speedoDisplay.needle_bar_highlight.attr({d: "M " + ex1 + "," + ey1 +
        " A" + radiusExtH  + "," + radiusExtH  + " 0 "+largeArcFlag+",1 " + ex2 + "," + ey2});
        speedoDisplay.needle_bar_highlightGrad.attr({x1: ex1, y1: ey1, x2: ex2, y2: ey2});

        
      }
    }
    function updateTachoDisplays(data) {
      if (speedoInitialised) {
        var startAngle=-145.15/*180*Math.PI/180*/, speedRad = (data["electrics"]["rpmTacho"] *rpmRatio)-startAngle;
        var maxRad = (-120*Math.PI/180) + startAngle;
        speedRad = Math.max(speedRad, maxRad);
        if(Math.abs(speedRad-cachedAng.tacho)<refreshAng){return;}
        cachedAng.tacho = speedRad;
        var centerX=185, centerY=31.5, radiusInt=15, radiusExt=83, largeArcFlag= ((speedRad-startAngle)>Math.PI)? 1 : 0, radiusExtH = -1 ;
        var sx2 = (centerX) + Math.cos(startAngle) * radiusInt ;
        var sy2 = (centerY) + Math.sin(startAngle) * radiusInt ;


        var sy1 = (centerY) + Math.sin(startAngle) * radiusExt;

        var ex2 = (centerX) + Math.cos(speedRad) * radiusExt ;
        var ey2 = (centerY) + Math.sin(speedRad) * radiusExt ;

        var ex1 = (centerX)  /*+ Math.cos(speedRad) * radiusInt*/;
        var ey1 = (centerY)  /*+ Math.sin(speedRad) * radiusInt*/;

        var mx1 = (centerX) + Math.cos(speedRad) * 20 ;
        var my1 = (centerY) + Math.sin(speedRad) * 20 ;

        tacho.bar.attr({d: "M " + 150 + "," + sy1 +
          " A" + radiusExt  + "," + radiusExt  + " 0 "+largeArcFlag+",0 " + ex2 + "," + ey2 +
          " L " + ex1 + "," + ey1 /*+
          " A" + radiusInt + "," + radiusInt + " 0 "+largeArcFlag+",1 " + sx2 + "," + sy2*/
        });
        tacho.needle.attr({d: "M " + ex1 + "," + ey1 + " " +ex2+","+ey2});


        ex2 = (centerX) + Math.cos(speedRad) * radiusExtH ;
        ey2 = (centerY) + Math.sin(speedRad) * radiusExtH ;

        ex1 = (centerX) + Math.cos(startAngle) * radiusExtH ;
        ey1 = (centerY) + Math.sin(startAngle) * radiusExtH ;
        tacho.rpm_needle_bar_highlight.attr({d: "M " + ex1 + "," + ey1 +
        " A" + radiusExtH  + "," + radiusExtH  + " 0 "+largeArcFlag+",0 " + ex2 + "," + ey2});
        tacho.rpm_needle_bar_highlightGrad.attr({x1: ex1, y1: ey1, x2: ex2, y2: ey2});



        
      }
    }
    $window.redrawSpeedoTicks = (lim,bigSep,smallSep) => {
      var startAngle=-180*Math.PI/180;
      var maxAngle = 150;
      var centerX=203.5, centerY=57.5, radiusInt=33.5, radiusExt=35, radiusIntBig=33.5;
      unitspeedratio = maxAngle*Math.PI/(lim*180)*3.4;
      var tickD = "";
      for(var ib = 0; ib<= (lim/bigSep) ; ib++){
        for(var is = 0; is<= (bigSep/smallSep); is++){
          var curAng = (ib*maxAngle/(lim/bigSep)+maxAngle*(1/(lim/bigSep))*(is/(bigSep/smallSep))) *Math.PI/180;
          if(curAng > (maxAngle*Math.PI/180)){break;}
          var sx2 = (centerX) + Math.cos(startAngle+curAng) * (is===0?radiusIntBig:radiusInt);
          var sy2 = (centerY) + Math.sin(startAngle+curAng) * (is===0?radiusIntBig:radiusInt);

          var sx1 = (centerX) + Math.cos(startAngle+curAng) * radiusExt;
          var sy1 = (centerY) + Math.sin(startAngle+curAng) * radiusExt;
          tickD += "M "+(sx1)+","+(sy1)+" "+(sx2)+","+(sy2)+" ";
        }
      }
      speedoDisplay.speedTicks.attr({d: tickD});
      var fontSize = 5;
      if(lim/bigSep > 12){
        fontSize = fontSize * (10/ (lim/bigSep)) ;
      }
    }
    $window.redrawTachoTicks = (lim,bigSep,smallSep,red) => {
      var startAngle=0;
      var maxAngle = -190;
      var centerX=67.7, centerY=57.5, radiusInt=34, radiusExt=36, radiusIntBig=34;
      rpmRatio = -70*Math.PI/(lim*170);

      var tickD = "";
      for(var ib = 0; ib<= (lim/bigSep) ; ib++){
        for(var is = 0; is<= (bigSep/smallSep); is++){
          var curAng = (ib*maxAngle/(lim/bigSep)+maxAngle*(1/(lim/bigSep))*(is/(bigSep/smallSep))) *Math.PI/180;
          if(curAng < (maxAngle*Math.PI/180)){break;}
          //console.log( (ib*270/(lim/bigSep)+270*(1/(lim/bigSep))*(is/(bigSep/smallSep))) , curAng);
          //console.log( "b=", ib*270/(lim/bigSep) , "s=", 270*(1/(lim/bigSep))*(is/(bigSep/smallSep)))
          var sx2 = (centerX) + Math.cos(startAngle+curAng) * (is===0?radiusIntBig:radiusInt);
          var sy2 = (centerY) + Math.sin(startAngle+curAng) * (is===0?radiusIntBig:radiusInt);

          var sx1 = (centerX) + Math.cos(startAngle+curAng) * radiusExt;
          var sy1 = (centerY) + Math.sin(startAngle+curAng) * radiusExt;
          tickD += "M "+(sx1)+","+(sy1)+" "+(sx2)+","+(sy2)+" ";
        }
      }
      var txtRadius = 41;
      tacho.Ticks.attr({d: tickD});
      var testStyle = {"font-style":"normal","font-weight":"bold","font-stretch":"normal","font-family":"Nasalization","fill-opacity":1,"stroke-width":0.04861574,"text-align":"center","text-anchor":"middle"};
      tacho.TicksText.empty();
      for(var ib = 0; ib<=(lim/bigSep) ; ib++){
        var curAng = (ib*maxAngle/(lim/bigSep)) *Math.PI/180;
        var sx = (centerX) + Math.cos(startAngle+curAng) * txtRadius;
        var sy = (centerY + 0.90) + Math.sin(startAngle+curAng) * txtRadius;
        var ts = hu('<tspan>', tacho.TicksText)
        .attr({x: sx,y: sy})
        .text((ib*bigSep*0.001))
        .css(testStyle)
        .css({"fill":(ib*bigSep >= red)?"#ef3535":"#fff"});
      }

    }
    function fixClock(v, fill="0"){
      return (v<10)? fill+v : v;
      
    }
    function downdash (data) {
      const current_time = new Date(Date.now());
      var pid = fixClock(current_time.getMinutes());
      downD.time.text(fixClock(current_time.getHours(), " ") + ":" + pid) ;
      //nex
      let envTemp = UiUnits.temperature(data.customModules.environmentData.temperatureEnv)
      downD.temp.text("+" + envTemp.val.toFixed(0));
      downD.speeds.text((data.electrics.wheelspeed * (unit=="metric"?3.6:2.23694) ).toFixed(0));
      second.vert.width(((data["electrics"]["rpmTacho"]/195)));

      dd2.tm2.text(fixClock(current_time.getHours(), " ") + ":" + pid) ;
      dd2.tmo2.text("+" + envTemp.val.toFixed(0));
      dd2.speeds2d.text((data.electrics.wheelspeed * (unit=="metric"?3.6:2.23694) ).toFixed(0));
    }
    function gearind (data) {
      if (currentGear !== data.electrics.gear) {
        currentGear = data.electrics.gear;
        var xct = -1;
        if(isNaN(data.electrics.gear)){//auto,DCT
          speedoDisplay.gears["P"].n.style.display = "inline"; //because why not at this point
          if(data.electrics.gear.length >1){
            xct-= (data.electrics.gear[0]=="M")?5:2;
          }
          for (var key in speedoDisplay.gears) {
            if (key === data.electrics.gear) {
              speedoDisplay.gears[key].css({ fill: '#FFFFFF'});
              xct += 4;
            }
            else {
              speedoDisplay.gears[key].css({ fill: '#fff0'});
            }
          }
          if(xct <= 0){
            speedoDisplay.gears["D"].css({ fill: '#FFFFFF'}).text(currentGear);
          }
          else{
            speedoDisplay.gears["D"].text("D");
          }
        }else{//manuel
          speedoDisplay.gears["P"].n.style.display = "none";
          switch(data.electrics.gear){
            case -1:
              speedoDisplay.gears["R"].css({ fill: '#FFFFFF'});
              speedoDisplay.gears["N"].css({ fill: '#fff0'});
              speedoDisplay.gears["D"].css({ fill: '#fff0'}).text("1");
              break;
            case 0:
              speedoDisplay.gears["R"].css({ fill: '#fff0'});
              speedoDisplay.gears["N"].css({ fill: '#FFFFFF'});
              speedoDisplay.gears["D"].css({ fill: '#fff0'});//.text("1");
              break;
            default:
              speedoDisplay.gears["R"].css({ fill: '#fff0'});
              speedoDisplay.gears["N"].css({ fill: '#fff0'});
              speedoDisplay.gears["D"].css({ fill: '#FFFFFF'}).text(data.electrics.gear);
              break;
            }
          }
        }

      }
      function gearindVERT (data) {
        if (currentGearG !== data.electrics.gear) {
          currentGearG = data.electrics.gear;
          var xct = -1;
          if(isNaN(data.electrics.gear)){//auto,DCT
            dd2.ggrr["P"].n.style.display = "inline"; //because why not at this point
            if(data.electrics.gear.length >1){
              xct-= (data.electrics.gear[0]=="M")?5:2;
            }
            for (var key in dd2.ggrr) {
              if (key === data.electrics.gear) {
                dd2.ggrr[key].css({ fill: '#FFFFFF'});
                xct += 4;
              }
              else {
                dd2.ggrr[key].css({ fill: '#fff0'});
              }
            }
            if(xct <= 0){
              dd2.ggrr["D"].css({ fill: '#FFFFFF'}).text(currentGearG);
            }
            else{
              dd2.ggrr["D"].text("D");
            }
          }else{//manuel
            dd2.ggrr["P"].n.style.display = "none";
            switch(data.electrics.gear){
              case -1:
                dd2.ggrr["R"].css({ fill: '#FFFFFF'});
                dd2.ggrr["N"].css({ fill: '#fff0'});
                dd2.ggrr["D"].css({ fill: '#fff0'}).text("1");
                break;
              case 0:
                dd2.ggrr["R"].css({ fill: '#fff0'});
                dd2.ggrr["N"].css({ fill: '#FFFFFF'});
                dd2.ggrr["D"].css({ fill: '#fff0'});//.text("1");
                break;
              default:
                dd2.ggrr["R"].css({ fill: '#fff0'});
                dd2.ggrr["N"].css({ fill: '#fff0'});
                dd2.ggrr["D"].css({ fill: '#FFFFFF'}).text(data.electrics.gear);
                break;
              }
            }
          }

    }
    $window.setup = (data) => {
      if(!ready){
        console.log("calling setup while svg not fully loaded");
        setTimeout(function(){ $window.setup(data) }, 100);
        return;
      }
      for(let dk in data){
        if(typeof dk == "string" && dk.startsWith("uiUnit")){
          units[dk] = data[dk];
        }
      }
      
      vueEventBus.emit('SettingsChanged', {values:units})
        redrawTachoTicks(data.maxRPM,1000,1500,data.redRPM);
    }
    $window.initMap = (data) => {
      navDimensions = data.viewParams = [
        data.terrainOffset[0],
        data.terrainOffset[1],
        data.terrainSize[0],
        data.terrainSize[1]
      ];
      $scope.$apply(() => {
        vm.mapData = data;
      });

      navContainer.style.width = data.terrainSize[0] + "px";
      navContainer.style.height = data.terrainSize[1] + "px";
    }
    $window.updateMap = (data) => {
      var focusX = -data.x;
      var focusY = data.y;
      var origin = `${((navDimensions[0] * -1)) - focusX}px ${((navDimensions[1] * -1)) - focusY}px`;
      navContainer.style.transformOrigin = origin;
      var translateX = ((((navDimensions[0])) + 512) + focusX);
      var translateY = ((((navDimensions[1])) + 256) + focusY);
      navContainer.style.transform = `translate3d(${translateX}px,${translateY}px, 0px) rotateX(${55}deg) rotateZ(${180 + (data.rotation + 360)}deg) scale(1)`;
    }
    function setElec(val, state, key){
      if( val === undefined || val === null){console.error("setElec: svg element not found", key); return;}
      if( state === undefined || state === null){console.error("setElec: state not found", key);val.n.style.display = "none"; return;}
      var cssState = (state===true || state>0.1)?"inline":"none";
      val.n.style.display = cssState;
    }

    

    

    function isColor(strColor){
      var s = new Option().style;
      s.color = strColor;
      return s.color !== "";
    }

    $window.updateMode = (data) => {
      if(!ready){
        console.log("calling updateMode while svg not fully loaded");
        setTimeout(function(){ $window.updateMode(data) }, 100);
        return;
      }
      if(data === null
        || data === undefined
        || data.modeName === null
        || data.modeName === undefined
        || typeof data.modeName !== "string"
        || data.modeColor === null
        || data.modeColor === undefined
        || typeof data.modeColor !== "string"){
          console.error("updateMode receive wrong arguments :", data);
          document.getElementById("tspan995").innerHTML = "MODE";
          return;
        }

  
        //hex color without # works in html but not in svg BECAUSE
        painduchocolat.root.n.style.display = "none";
        var s = new Option().style;
        s.color = data.modeColor;
        data.modeColor = s.color;

      var vertical = data.modeName == "vertic";
      var sportvis = data.modeName == "comf";


      if (vertical === true) {
        second.root.css({opacity: 1});
        first.root.css({opacity: 0});
        speedoDisplay.root.css({opacity: 0});
        tacho.root.css({opacity: 0});
        downD.root.css({opacity: 0});
        dd2.root.css({opacity: 1});
        console.log("ready");
      }
        if (sportvis === true) {
        second.root.css({opacity: 0});
        first.root.css({opacity: 1});
        speedoDisplay.root.css({opacity: 1});
        tacho.root.css({opacity: 1});
        downD.root.css({opacity: 1});
        dd2.root.css({opacity: 0});
        console.log("ggg");


      }
      }
    $window.updateData = (data) => {
      if (data) {
        if(!ready){console.log("not ready");return;}
        updateSpeedDisplays(data);
        updateTachoDisplays(data);
        downdash(data);
        gearind (data);
        gearindVERT (data);
      }
    }
  });