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

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

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

        if (!svg) return;

        needle = svg.getElementById('needle');

        if (!needle) return;

        function updateFuelGauge(fuelLevel) {
          const minDegree = 169;
          const maxDegree = 249;
          const rotationDegree = minDegree + (fuelLevel * (maxDegree - minDegree));
          needle.setAttribute('transform', `rotate(${rotationDegree}, 1, 60)`);
        }

        scope.$on('streamsUpdate', function (event, streams) {
          if (svg && needle) {
            let fuelLevel = streams.engineInfo[11] / streams.engineInfo[12];
            updateFuelGauge(fuelLevel);

            if (!visible) {
              element[0].style.opacity = 1;
              visible = true;
            }
          }
        });
      });

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