'use strict';
angular.module('beamng.apps')
.directive('sgrSpeedo', ['$log', function ($log) {
  return {
    template: '<object style="width:100%; height:100%;" type="image/svg+xml" data="/ui/modules/apps/SGRSpeedo/SGRSpeedo.svg"></object>',
    replace: true,
    restrict: 'EA',
    scope: true,
    link: function (scope, element) {
      element.css({ transition: 'opacity 0.3s ease' });
      let visible = false;
      let svg;
      let totalDistance = 0;
      let lastUpdateTime = null;

      function loadSavedOdometer() {
        const savedDistance = localStorage.getItem('odometerDistance');
        if (savedDistance) {
          totalDistance = parseFloat(savedDistance);
        }
      }

      function saveOdometer() {
        localStorage.setItem('odometerDistance', totalDistance);
      }

      function initializeSvg() {
        svg = element[0].contentDocument;

        if (!svg) {
          return;
        }

        let needle = svg.getElementById('needle');
        let odometerDigits = [
          svg.getElementById('odometerDigit1'),
          svg.getElementById('odometerDigit2'),
          svg.getElementById('odometerDigit3'),
          svg.getElementById('odometerDigit4'),
          svg.getElementById('odometerDigit5'),
          svg.getElementById('odometerDigit6')
        ];
        let odometerDecimalPoint = svg.getElementById('odometerDecimalPoint');
        let resetButton = svg.getElementById('reset_button');

        if (!needle || odometerDigits.some(digit => !digit) || !odometerDecimalPoint || !resetButton) {
          return;
        }

        function initializeOdometer() {
          updateOdometerDisplay(totalDistance / 1609.34);
        }

        function updateNeedleRotation(currentSpeed) {
          const maxSpeed = 160;
          let rotationDegree;

          if (currentSpeed <= 10) {
            rotationDegree = (currentSpeed / 10) * 5 + 72;
          } else if (currentSpeed <= 20) {
            rotationDegree = ((currentSpeed - 10) / 10) * 20 + 77;
          } else if (currentSpeed <= maxSpeed) {
            rotationDegree = ((currentSpeed - 20) / (maxSpeed - 20)) * 245 + 97;
          } else {
            let extraSpeed = currentSpeed - maxSpeed;
            rotationDegree = 343 + (extraSpeed * 2);
          }

          needle.setAttribute('transform', `rotate(${rotationDegree}, 1, -20)`);
        }

        function updateOdometerDisplay(distance) {
          let distanceString = distance.toFixed(1).padStart(7, '0');
          for (let i = 0; i < 5; i++) {
            odometerDigits[i].textContent = distanceString[i];
          }
          odometerDecimalPoint.textContent = '.';
          odometerDigits[5].textContent = distanceString[6];
        }

        function resetOdometer() {
          totalDistance = 0;
          updateOdometerDisplay(totalDistance);
          saveOdometer();
        }

        resetButton.addEventListener('click', resetOdometer);

        scope.$on('streamsUpdate', function (event, streams) {
          if (svg && needle) {
            let currentSpeed = streams.electrics.wheelspeed;
            updateNeedleRotation(currentSpeed * 2.23694);

            let currentTime = Date.now();
            if (lastUpdateTime !== null) {
              let timeElapsed = (currentTime - lastUpdateTime) / 1000;
              let distanceIncrement = currentSpeed * timeElapsed;
              totalDistance += distanceIncrement;
              updateOdometerDisplay(totalDistance / 1609.34);
              saveOdometer();
            }
            lastUpdateTime = currentTime;

            if (!visible) {
              element[0].style.opacity = 1;
              visible = true;
            }
          }
        });

        loadSavedOdometer();
        initializeOdometer();

        scope.$on('$destroy', function () {
          if (svg && svg.getStreams) StreamsManager.remove(svg.getStreams());
          saveOdometer();
        });
      }

      element.on('load', initializeSvg);
    }
  };
}]);
