var angular = require('angular');
require('../modules');

var module = angular.module('commons.directives.sinofocus');

module.directive('sinoFocus', function($timeout, $parse) {
  function setSelectionRange(element, start, end) {
    if (element.setSelectionRange) {
      element.setSelectionRange(start, end);
    } else if (element.createTextRange) {
      var range = element.createTextRange();
      range.collapse(true);
      range.moveEnd('character', end);
      range.moveStart('character', start);
      range.select();
    }
  }

  return {
    restrict: 'A',
    replace: false,
    link: function(scope, element, attrs) {
      var sinoFocus = $parse(attrs.sinoFocus)(scope);
      if (sinoFocus === true) {
        $timeout(function() {
          element[0].focus();
        }, 100);
      }

      element.on('focus', function() {
        var value = element[0].value,
          length = value? value.length : 0;
        if (length > 0) {
          setSelectionRange(element[0], length, length);
        }
      });
    }
  };
});
