/**
 * Expects items array defined as following:
 * 
 * items = [{ name : 'name', value: 'value', category: 'category' }]
 * 
 * Selected conditions have selected : true
 * 
 */
angular.module("app").directive("itemsChooser", function ($rootScope, $timeout, UniqueIdGenerator, L) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/itemsChooser/itemsChooser.html",
        scope: {
            instance: '=',
            maxSelected: '@',
            noResultsText: '@',
            placeholder: '@',
            multiSelect: '@',
            afterInit: '=',
        },
        link: function (scope, element, attrs) {

            scope.instance.init = function (items, selectCallback, selectItem) {
                scope.categories.length = 0;

                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    var index = getCategoryIndex(scope.categories, item.category);

                    scope.categories[index].options.push(item);
                }

                var selectId = '#' + scope.chooserId + "-chosen-select";

                $timeout(function () {
                    if (chooserObj) chooserObj.destroy();

                    if (!scope.multiSelect) {
                        $(selectId).removeAttr('multiple');
                    }

                    chooserObj = $(selectId).chosen({
                        max_selected_options: scope.maxSelected,
                        no_results_text: scope.noResultsText
                    });

                    $(selectId).on('chosen:showing_dropdown', function (evt, params) {
                        window.activeChosen = true;
                    });

                    $(selectId).on('chosen:hiding_dropdown', function (evt, params) {
                        window.activeChosen = false;
                    });

                    chooserObj = chooserObj.data('chosen');

                    if(chooserObj){
                        chooserObj.setSelectCallback(selectCallback);
                        chooserObj.enableSameChoices();
    
                        initialized = true;
    
                        if (selectItem) {
                            chooserObj.selectItem(selectItem);
                        }
                    }
                }, 0, false);
            }

            scope.instance.getSelectedItems = function () {
                return chooserObj.getChoices();
            }

            scope.instance.clearSelection = function () {
                if (chooserObj) {
                    chooserObj.clearChoices();
                }
            }

            scope.instance.containsItem = function (item) {
                for (var i = 0; i < scope.categories.length; i++) {
                    var category = scope.categories[i];
                    if (getItem(category.options, 'value', item)) return true;
                }
                return false;
            }

            scope.instance.selectItem = function (item) {
                return chooserObj.selectItem(item);
            }

            scope.instance.enableSameChoices = function () {
                chooserObj.enableSameChoices();
            }

            scope.instance.disableSameChoices = function () {
                chooserObj.disableSameChoices();
            }

            function getCategoryIndex(categories, categoryName) {
                categoryName = categoryName || 'General';

                for (var i = 0; i < categories.length; i++) {
                    var category = categories[i].name;
                    if (category == categoryName) return i;
                }

                categories.push({
                    name: categoryName,
                    options: []
                });
                return categories.length - 1;
            }

            scope.$on("$destroy", function () {
                UniqueIdGenerator.removeId(scope.chooserId);
            });

            var initialized = false;
            var chooserObj;

            scope.chooserId = UniqueIdGenerator.generateId();
            scope.categories = scope.categories || [];
            scope.multiSelect = scope.multiSelect || false;
            scope.maxSelected = scope.maxSelected || 1000;
            scope.noResultsText = scope.noResultsText || '';
            scope.placeholder = scope.placeholder || L.tsq('Select conditions');

            scope.categories = [];

            if (scope.afterInit) {
                $timeout(scope.afterInit, 0, false);
            }
        }
    };
});