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

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

      function saveOdometer() {
        localStorage.setItem('SGRSilverodometertachDistance', 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 rpmNeedle = svg.getElementById('rpmneedle');
        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 || !rpmNeedle || odometerDigits.some(d => !d) || !odometerDecimalPoint || !resetButton) {
          return;
        }

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

        function updateOdometerDisplay(distanceMiles) {
          let distanceString = distanceMiles.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(0);
          saveOdometer();
        }

        resetButton.addEventListener('click', resetOdometer);

        function updateSpeedNeedleRotation(currentSpeedMPH) {
          const maxSpeed = 160;
          const maxRotation = 250;
          let rotationDegree = Math.min((currentSpeedMPH / maxSpeed) * maxRotation, maxRotation);
          rotationDegree += startRotation;
          needle.setAttribute('transform', `rotate(${rotationDegree}, 0, -7)`);
        }

        function updateRPMNeedleRotation(currentRPM) {
          const maxRPM = 10000;
          let ratio = currentRPM / maxRPM;
          if (ratio > 1) ratio = 1;
          let rotationDegree = rpmStartDeg + (rpmMaxDeg - rpmStartDeg) * ratio;
          rpmNeedle.setAttribute('transform', `rotate(${rotationDegree}, 5, 95)`);
        }

        scope.$on('streamsUpdate', function (event, streams) {
          if (!visible) {
            element[0].style.opacity = 1;
            visible = true;
          }
          let currentSpeedMPS = streams.electrics.wheelspeed || 0;
          let currentSpeedMPH = currentSpeedMPS * 2.23694;
          updateSpeedNeedleRotation(currentSpeedMPH);
          let currentRPM = streams.electrics.rpm || 0;
          updateRPMNeedleRotation(currentRPM);
          let currentTime = Date.now();
          if (lastUpdateTime !== null) {
            let timeElapsed = (currentTime - lastUpdateTime) / 1000;
            let distanceIncrementM = currentSpeedMPS * timeElapsed;
            totalDistance += distanceIncrementM;
            updateOdometerDisplay(totalDistance / 1609.34);
            saveOdometer();
          }
          lastUpdateTime = currentTime;
        });

        loadSavedOdometer();
        initializeOdometer();

        scope.$on('$destroy', function () {
          saveOdometer();
        });
      }

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