'use strict';
angular.module('beamng.apps')
.directive('sgrsilverprocompPsi', ['$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/sgrsilverprocompPsi/sgrsilverprocompPsi.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.currentPsi = 0;

      const psiToDegreeMap = [
        { psi: 0, degree: -48 },
        { psi: 35, degree: 227 }
      ];

      function interpolatePsiToDegree(psi) {
        for (let i = 0; i < psiToDegreeMap.length - 1; i++) {
          const pointA = psiToDegreeMap[i];
          const pointB = psiToDegreeMap[i + 1];

          if (psi >= pointA.psi && psi <= pointB.psi) {
            const ratio = (psi - pointA.psi) / (pointB.psi - pointA.psi);
            return pointA.degree + ratio * (pointB.degree - pointA.degree);
          }
        }
        return psiToDegreeMap[psiToDegreeMap.length - 1].degree;
      }

      function updateNeedleRotation(psi) {
        const rotationDegree = interpolatePsiToDegree(psi);
        if (needle) {
          needle.setAttribute('transform', `rotate(${rotationDegree}, 3, -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.boost !== undefined) {
              scope.currentPsi = Math.max(0, Math.min(data.electrics.boost, 100));
              updateNeedleRotation(scope.currentPsi);
            }
          });
        }, 500);
      });

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