import template from './ws-fancy-percent.html';

export default function FancyPercentDirective() {
  return {
    restrict: 'E',
    template,
    scope: {
      number: '@',
      color: '@?',
      toFixed: '@?',
    },
    link(scope, element) {
      scope.$watch('number', setPercentage);

      scope.NO_NUMBER_SYMBOL = '−';

      function setPercentage() {
        scope.percentage = parseFloat(scope.number);

        if (scope.color === 'true') {
          const container = angular.element(element[0].querySelector('.ws-fancy-formatting'));
          if (scope.percentage > 0) {
            container.addClass('positive');
          } else if (scope.percentage < 0) {
            container.addClass('negative');
          } else {
            container.addClass('zero');
          }
        }

        if (isNaN(parseFloat(scope.number))) {
          scope.percentage = scope.NO_NUMBER_SYMBOL;
        }
      }

      scope.isNoNumberSymbol = value =>
        value === scope.NO_NUMBER_SYMBOL;
    },
  };
}
