import ngModule from '../module';

export function focus(input) {
    let selector = 'input, textarea, button, submit';

    if (!input.matches(selector))
        input = input.querySelector(selector);

    if (!input) {
        console.warn(`vnFocus: Can't find a focusable element`);
        return;
    }

    input.focus();

    if (input.select)
        input.select();
}

/**
 * Sets the focus and selects the text on the input.
 *
 * @return {Object} The directive
 */
export function directive() {
    return {
        restrict: 'A',
        link: function($scope, $element) {
            $scope.$watch('', () => focus($element[0]));
        }
    };
}
ngModule.directive('vnFocus', directive);