import ngModule from '../module';
import {kebabToCamel} from '../lib/string';

/**
 * Registers the element controller into the scope as a property whose name is
 * the directive value transformed to lowerCamelCase.
 *
 * @return {Object} The directive
 */
export function directive() {
    return {
        restrict: 'A',
        link: function($scope, $element, $attrs) {
            let id = kebabToCamel($attrs.vnId);

            if (!id)
                throw new Error(`vnId: Attribute can't be null`);

            let $ctrl = $element[0].$ctrl
                ? $element[0].$ctrl
                : $element.controller($element[0].tagName.toLowerCase());
            let ctrl = $ctrl || $element[0];

            $scope[id] = ctrl;

            if (!$scope.hasOwnProperty('$ctrl')) {
                while ($scope && !$scope.hasOwnProperty('$ctrl'))
                    $scope = Object.getPrototypeOf($scope);

                if ($scope) $scope[id] = ctrl;
            }
        }
    };
}
ngModule.directive('vnId', directive);