define(['cla_angular',
        './tag_picker.html',
        '../../../../../web/intranet/js/tags/jquery.timers.js',
        '../../../../../web/intranet/js/tags/jquery.tagInput.js',
        '../../../../../web/intranet/js/tags/jquery.tagInput.css'], function (angular, template) {

    var moduleName = 'cla.core.tag_picker';
    var module = null;
    try {
        module = angular.module(moduleName);
    } catch(err) {
        // named module does not exist, so create one
        module = angular.module(moduleName, []);
    }

    module.directive('claTagPicker', tagPicker);

    function tagPicker() {
        controller.$inject = ['$timeout', '$element'];
        function controller($timeout, $element)
        {
            var ctrl = this;

            this.$onInit = function() {
                if (typeof ctrl.suggestedTags === 'string')
                    ctrl.suggested = ctrl.suggestedTags.split(',');
                else
                    ctrl.suggested = [];

            ctrl.control.reset = function()
            {
                $timeout(function(){
                    angular.element($element).find('.form-text.text-muted').remove();
                        angular.element($element).find('input[name=tags_input]').tagInput({
                            tags: ctrl.ngModel,
                            sortBy:"frequency",
                            suggestedTags: ctrl.suggested,
                            tagSeparator: ", ",
                            autoFilter:true,
                            autoStart:false,
                            boldify:true
                        });
                    }, 0);
                };
                ctrl.control.reset();
            };
        }

        return {
            controller: controller,
            bindToController: true,
            controllerAs: 'picker',
            restrict: 'E',
            require: '^ngModel',
            templateUrl: template,
            scope: {
                ngModel: '=',
                control: '=',
                context: '@',
                suggestedTags: '@'
            }
        };
    }
});

window.jquery_tagInput_js_suggested_tags_text = lmsg('common.tags.popular_tags') + ': ';
