'use strict';
/**
 * Implements directive for qusion.table component.
 */
var qnLibraryselector = angular.module('libraries.directives.selector', [])
    .directive('qnLibraryselector', [

        function () {
            return {
                require: '?ngModel',
                replace: true,
                scope: {
                    options: "=qnLibraryselector",
                    ui: "&ui",
                    selectedLibraries: "=ngModel"
                },
                templateUrl: '/areas/qusion/scripts/templates/libraries/selector.html',
                controller: function ($scope, ImageService, LibraryService) {
                    $scope.selectedLibrary = 0;
                    $scope.selected = [];
                    $scope.loadLibraries = function() {
                        ImageService.libraries().then(function(data) {
                            $scope.libraries = data;
                        });
                    };

                    $scope.ui.dialogSelect = {
                        width: 715,
                        create: function () {
                            $(".ui-widget-header").hide();
                            $scope.selectionComplete = false;
                            $scope.dialogSelect = $(this);
                        },
                        close: function () {
                            if ($scope.selectionComplete == false) {

                            }
                        }
                    };

                    $scope.selectLibraries = function () {
                        $scope.dialogSelect.dialog("open");
                    };
                    
                    $scope.$watch('selectedLibraries', function (value) {
                        $scope.selected = value;
                    }, true);

                    $scope.loadLibraries();
                },
                link: function (scope, element, attr, ngModel) {

                    scope.doneSelection = function () {

                        scope.selected = [];
                        scope.selectedTitles = [];
                        angular.forEach(scope.selectedItems, function (value, key) {
                            scope.selected.push(value.ID);
                        });

                        scope.selectedLibraries = scope.selected;
                        scope.dialogSelect.dialog("close");
                    };

                    scope.cancelSeletion = function () {
                        scope.dialogSelect.dialog("close");
                    };



                }
            };
        }
    ]);