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

FancyCurrencyDirective.$inject = ['ISO_CODE_TO_SYMBOL_MAP'];
export default function FancyCurrencyDirective(ISO_CODE_TO_SYMBOL_MAP) {
  return {
    restrict: 'E',
    template,
    scope: {
      number: '@',
      toFixed: '@?',
      symbol: '@?',
      currencyIsoCode: '@?',
      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 ||
          ISO_CODE_TO_SYMBOL_MAP[scope.currencyIsoCode] ||
          '$';
        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;
    },
  };
}
