'use strict';
angular.module('beamng.apps')
.directive('sgrPsi', ['$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/SGRPsi/SGRPsi.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: -277 },
        { psi: 5, degree: -251 },
        { psi: 10, degree: -212 },
        { psi: 15, degree: -174 },
        { psi: 20, degree: -139 },
        { psi: 25, degree: -101 },
        { psi: 30, degree: -65 },
        { psi: 35, degree: -26 }
      ];

      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}, 1, -20)`);
        }
      }

      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, 35));
              updateNeedleRotation(scope.currentPsi);
            }
          });
        }, 500);
      });

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