define(['cla_angular', 'document_picker', './document_picker.html', '../lmsg.directive.js'], function (angular, documentPickerClass, template) {
    var moduleName = 'cla.core.document_picker';
    try {
        var module = angular.module(moduleName);
    } catch (err) {
        // named module does not exist, so create one
        var module = angular.module(moduleName, ['cla.core.lmsg']);
    }

    module.directive('claDocumentPicker', documentPicker);

    function documentPicker() {

        controller.$inject = ['$scope'];

        return {
            controllerAs: 'ctrl',
            controller: controller,
            link: link,
            restrict: 'E',
            require: '^ngModel',
            templateUrl: template,
            scope: {
                ngModel: '=',
                documentName: '@',
                unique: '@',
                control: '='
            }
        };

        function controller($scope) {
            var ctrl = this;

            this.$onInit = function () {
                ctrl.id           = 'documentPicker' + $scope.unique;
                ctrl.buttonId     = 'documentPickerSelect' + $scope.unique;
                ctrl.hiddenId     = 'documentPickerHidden' + $scope.unique;
                ctrl.documentId   = $scope.ngModel;
                ctrl.documentName = $scope.documentName;
            };
        }

        function link(scope, iElement, iAttrs, ctrl) {

            scope.id       = 'documentPicker' + scope.unique;
            scope.buttonId = 'documentPickerSelect' + scope.unique;
            scope.hiddenId = 'documentPickerHidden' + scope.unique;

            scope.init = function () {
                setTimeout(function() {
                    var documentPicker = new documentPickerClass(scope.id, scope.buttonId, scope.hiddenId);
                    documentPicker.init();
                }, 0);
            };

            scope.onChange = function () {
                value         = document.getElementById(scope.hiddenId).value;
                scope.ngModel = parseInt(value);
                ctrl.$setViewValue(scope.ngModel);
            };

            scope.internalControl       = scope.control || {};
            scope.internalControl.reset = function () {
                // Rebind the model. This shouldn't be needed but it never gets updated once reset otherwise
                ctrl.$setViewValue(scope.ngModel);

                scope.init();
            };

            scope.init();
        }
    }
});
