import template from './ws-fancy-currency.tmpl.html';

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

      scope.NO_NUMBER_SYMBOL = '−';

      function setCurrencyNumber() {
        const parsedNumber = parseFloat(scope.number);
        scope.sign = parsedNumber < 0 ? '-' : '';
        scope.currencySymbol = scope.symbol || '$';
        scope.currencyNumber = Math.abs(parsedNumber);

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

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

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