'use strict';
angular.module('beamng.apps')
.directive('sgrsilverprocompFuel', ['$log', '$timeout', function ($log, $timeout) {
  return {
    template: `
      <div style="width: 100%; height: 100%; position: relative;">
        <object style="width:100%; height:100%;" type="image/svg+xml" data="/ui/modules/apps/sgrsilverprocompFuel/sgrsilverprocompfuel.svg"></object>
      </div>
    `,
    replace: true,
    restrict: 'EA',
    scope: true,
    link: function (scope, element) {
      element.css({ transition: 'opacity 0.3s ease' });
      let svg;
      let needle;
      scope.currentfuel = 0;
      const fuelToDegreeMap = [
        { fuel: 0, degree: 43 },
        { fuel: 1, degree: 137 }
      ];
      function interpolateFuelToDegree(fuel) {
        for (let i = 0; i < fuelToDegreeMap.length - 1; i++) {
          const a = fuelToDegreeMap[i];
          const b = fuelToDegreeMap[i + 1];
          if (fuel >= a.fuel && fuel <= b.fuel) {
            const ratio = (fuel - a.fuel) / (b.fuel - a.fuel);
            return a.degree + ratio * (b.degree - a.degree);
          }
        }
        return fuelToDegreeMap[fuelToDegreeMap.length - 1].degree;
      }
      function updateNeedleRotation(fuel) {
        const rotationDegree = interpolateFuelToDegree(fuel);
        if (needle) {
          needle.setAttribute('transform', `rotate(${rotationDegree}, 11, 25)`);
        }
      }
      element[0].querySelector('object').addEventListener('load', function () {
        $timeout(function () {
          svg = element[0].querySelector('object').contentDocument;
          if (!svg) return;
          needle = svg.getElementById('needle');
          if (!needle) return;
          scope.$on('streamsUpdate', function (event, data) {
            if (svg && needle && data.electrics && data.electrics.fuel !== undefined) {
              scope.currentfuel = Math.max(0, Math.min(data.electrics.fuel, 1));
              updateNeedleRotation(scope.currentfuel);
            }
          });
        }, 500);
      });
      scope.$on('$destroy', function () {
        if (svg && svg.getStreams) StreamsManager.remove(svg.getStreams());
      });
    }
  };
}]);
