'use strict';
angular.module('beamng.apps')
.directive('sgrsilverprocompSpeedo', ['$log', function ($log) {
  return {
    template: '<object style="width:100%; height:100%;" type="image/svg+xml" data="/ui/modules/apps/sgrsilverprocompSpeedo/sgrsilverprocompSpeedo.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;
      let startRotation = 15;

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

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

      function injectFontStyle() {
        const styleElement = document.createElement('style');
        styleElement.textContent = `
          @font-face {
            font-family: 'DS-Digital';
            src: url('/ui/common/DS-DIGII.ttf') format('truetype');
          }
          text {
            font-family: 'DS-Digital', sans-serif;
          }
        `;
        const svgRoot = svg.querySelector('svg');
        if (svgRoot) {
          svgRoot.appendChild(styleElement);
        }
      }

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

        if (!svg) {
          return;
        }

        injectFontStyle();

        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 = 260;
          const maxRotation = 270;
          let rotationDegree = Math.min((currentSpeed / maxSpeed) * maxRotation, maxRotation) + startRotation;

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

        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);
    }
  };
}]);
