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

      scope.SGRsilver = parseInt(localStorage.getItem('SGRsilver')) || 5000;

      var streamsList = ['engineInfo'];
      StreamsManager.add(streamsList);

      function saveSGRsilver() {
        localStorage.setItem('SGRsilver', scope.SGRsilver);
      }

      element.on('load', function () {
        svg = element[0].contentDocument;

        let needle = svg.getElementById('needle');
        let shiftLightOff = svg.getElementById('shift_light');
        let shiftLightOn = svg.getElementById('shift_light_on');
        let upBtn = svg.getElementById('up_btn');
        let downBtn = svg.getElementById('down_btn');

        if (!needle || !shiftLightOff || !shiftLightOn || !upBtn || !downBtn) return;

        function updateNeedleRotation(currentRPM) {
          if (currentRPM < 50) return;
          const maxRPM = 11000;
          const offset = -61;
          const rotationDegree = (currentRPM / maxRPM) * 240 + offset;
          needle.setAttribute('transform', `rotate(${rotationDegree}, 58.5, 24.5)`);
        }

        function updateShiftLight(currentRPM) {
          if (currentRPM >= scope.SGRsilver) {
            shiftLightOff.setAttribute('opacity', '0');
            shiftLightOn.setAttribute('opacity', '1');
          } else {
            shiftLightOff.setAttribute('opacity', '1');
            shiftLightOn.setAttribute('opacity', '0');
          }
        }

        function pointNeedleToSGRsilver() {
          const maxRPM = 11000;
          const offset = -61;
          const rotationDegree = (scope.SGRsilver / maxRPM) * 240 + offset;
          needle.setAttribute('transform', `rotate(${rotationDegree}, 58.5, 24.5)`);

          if (needleTimeout) {
            $timeout.cancel(needleTimeout);
          }

          needleTimeout = $timeout(function () {
            normalOperation = true;
          }, 2000);
        }

        upBtn.addEventListener('mousedown', function (event) {
          scope.$apply(function () {
            const increment = event.button === 2 ? 10 : 100;
            scope.SGRsilver = Math.min(11000, scope.SGRsilver + increment);
            saveSGRsilver();
            normalOperation = false;
            pointNeedleToSGRsilver();
          });
        });

        downBtn.addEventListener('mousedown', function (event) {
          scope.$apply(function () {
            const decrement = event.button === 2 ? 10 : 100;
            scope.SGRsilver = Math.max(0, scope.SGRsilver - decrement);
            saveSGRsilver();
            normalOperation = false;
            pointNeedleToSGRsilver();
          });
        });

        scope.$on('streamsUpdate', function (event, streams) {
          if (svg && needle && shiftLightOff && shiftLightOn) {
            let currentRPM = streams.engineInfo[4];
            if (normalOperation) {
              updateNeedleRotation(currentRPM);
            }
            updateShiftLight(currentRPM);
            if (!visible) {
              element[0].style.opacity = 1;
              visible = true;
            }
          }
        });
      });

      scope.$on('VehicleChange', function() {
        if (svg && svg.vehicleChanged) svg.vehicleChanged();
      });

      scope.$on('VehicleFocusChanged', function (event, data) {
        if (data.mode === true && svg && svg.vehicleChanged) {
          svg.vehicleChanged();
        }
      });

      scope.$on('$destroy', function () {
        StreamsManager.remove(streamsList);
      });
    }
  };
}]);
