'use strict';

var StringMask = require('string-mask');

var m = angular.module('ui.utils.masks.helpers', []);

module.exports = m.name;

m.factory('PreFormatters', [function() {
	function clearDelimitersAndLeadingZeros(value) {
		if (value === '0') {
			return '0';
		}

		var cleanValue = value.replace(/^-/,'').replace(/^0*/, '');
		return cleanValue.replace(/[^0-9]/g, '');
	}

	function prepareNumberToFormatter(value, decimals) {
		return clearDelimitersAndLeadingZeros((parseFloat(value)).toFixed(decimals));
	}

	return {
		clearDelimitersAndLeadingZeros: clearDelimitersAndLeadingZeros,
		prepareNumberToFormatter: prepareNumberToFormatter
	};
}])
	.factory('NumberMasks', [function() {
		return {
			viewMask: function(decimals, decimalDelimiter, thousandsDelimiter) {
				var mask = '#' + thousandsDelimiter + '##0';

				if (decimals > 0) {
					mask += decimalDelimiter;
					for (var i = 0; i < decimals; i++) {
						mask += '0';
					}
				}

				return new StringMask(mask, {
					reverse: true
				});
			},
			modelMask: function(decimals) {
				var mask = '###0';

				if (decimals > 0) {
					mask += '.';
					for (var i = 0; i < decimals; i++) {
						mask += '0';
					}
				}

				return new StringMask(mask, {
					reverse: true
				});
			}
		};
	}]);

@@ -286,24 +286,35 @@
 lue = value.
+toString().
 replace(/%5E-/

convert input value to string before replacing invalid characters