text: 'use strict';
  
  var StringMask = require('string-mask');
  var maskFactory = require('mask-factory');
  
  /**
   * FIXME: all numbers will have 9 digits after 2016.
   * see http://portal.embratel.com.br/embratel/9-digito/
   */
  var phoneMask8D = new StringMask('(00) 0000-0000'),
  	phoneMask9D = new StringMask('(00) 00000-0000'),
  	phoneMask8DSemDDD = new StringMask('0000-0000'),
  	phoneMask9DSemDDD = new StringMask('00000-0000'),
  	phoneMask0800 = new StringMask('0000-000-0000');
  
  module.exports = {
  	directive: maskFactory({
  		clearValue: function (rawValue) {
  			return rawValue.toString().replace(/[^0-9]/g, '').slice(0, 11);
  		},
  		format: function (cleanValue) {
  			return format(cleanValue)
  		},
  		getModelValue: function (formattedValue, originalModelType) {
  			var cleanValue = this.clearValue(formattedValue);
  
  			return originalModelType === 'number' ? parseInt(cleanValue) : cleanValue;
  		},
  		validations: {
  			phoneNumber: function (value) {
  				var valueLength = value && value.toString().length;
  				return valueLength === 8 || valueLength === 9 || valueLength === 10 || valueLength === 11;
  			}
  		}
  	}),
  	filter: BrPhoneFilter
  }
  
  function format(value) {
  
  	if (!value) return "";
  
  	var formatedValue;
  	if (value.indexOf('0800') === 0) {
  		formatedValue = phoneMask0800.apply(value);
  	} else if (value.length < 9) {
  		formatedValue = phoneMask8DSemDDD.apply(value) || '';
  	} else if (value.length < 10) {
  		formatedValue = phoneMask9DSemDDD.apply(value) || '';
  	} else if (value.length < 11) {
  		formatedValue = phoneMask8D.apply(value) || '';
  	} else {
  		formatedValue = phoneMask9D.apply(value);
  	}
  
  	return formatedValue.trim().replace(/[^0-9]$/, '');
  }
  
  function BrPhoneFilter($filter) {
  	return function (input) {
  		return format(input);
  	};
  }
  BrPhoneFilter.$inject = ['$filter'];