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

      const tempToDegreeMap = [
        { temp: 100, degree: -47 },
        { temp: 340, degree: 229 }
      ];

      function interpolateTempToDegree(temp) {
        for (let i = 0; i < tempToDegreeMap.length - 1; i++) {
          const pointA = tempToDegreeMap[i];
          const pointB = tempToDegreeMap[i + 1];

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

      function updateNeedleRotation(temp) {
        const rotationDegree = interpolateTempToDegree(temp);
        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.oiltemp !== undefined) {
              const tempF = (data.electrics.oiltemp * 9 / 5) + 32;

              scope.currenttemp = Math.max(100, Math.min(tempF, 260));

              updateNeedleRotation(scope.currenttemp);
            }
          });
        }, 500);
      });

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