angular.module("app").directive("itemsChooserModal", function ($rootScope, $timeout, UniqueIdGenerator, SQConstants, SkinService, L) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/itemsChooserModal/itemsChooserModal.html",
        scope: {
            instance: '=',
            maxSelected: '@',
            noResultsText: '@',
            placeholder: '@',
            multiSelect: '@',
            onAdd: '&',             //should return true to hide the popup
            title: '@',
            chooserLabel: '@',
            recentItems: '@',
            afterInit: '=',
        },
        link: function (scope, element, attrs) {

            var columnTypes = SQConstants.getConstants().databankColumnTypes;
            var columns = SQConstants.getColumnsByType([columnTypes.general, columnTypes.wfSpecial]);

            var allItemsClasses = [];

            scope.instance.init = function (items, selectCallback, selectItem) {
                scope.itemsChooser.init(items, selectCallback, selectItem);
                allItemsClasses = [];
                items.forEach(function (item) {
                    allItemsClasses.push(item.class);
                });
            }

            var defaultItemsPure = ["Fitness", "Symbol", "TimeFrame", "NetProfit", "MiniEquityChart", "NumberOfTrades", "PctWins", "ProfitFactor",
                "SharpeRatio", "RExpectancy", "AnnualPctReturn", "Stability", "Symmetry", "Drawdown", "WinLossRatio", "ReturnDDRatio", "AnnualPctReturnDDRatio",
                "AvgWin", "AvgLoss", "AvgBarsWin", "AvgBarsLoss", "AvgBarsInTrade", "Exposure"];

            var defaultItems = [];
            for (var i = 0; i < defaultItemsPure.length; i++) {
                defaultItems.push({
                    name: defaultItemsPure[i],
                    weight: 10 - (i / 3),
                    class: defaultItemsPure[i],
                });
            }

            var tagCloudInited = false;

            scope.instance.loadRecentItems = function (items, newDefaultItems) {
                scope.recentItemsList.length = 0;

                items = items || [];

                if (newDefaultItems != undefined) {
                    defaultItems = newDefaultItems;
                }

                for (var i = 0; i < items.length; i++) {
                    for (var j = defaultItems.length - 1; j > 0; j--) {
                        if (defaultItems[j].class == items[i].class) {
                            defaultItems.splice(j, 1);
                        }
                    }
                }

                items = items.concat(defaultItems);

                for (var i = 0; i < items.length; i++) {
                    if (scope.recentItemsList.length == 8) {
                        break;
                    }

                    var recentItem = items[i].class;
                    var columnObj = getItem(columns, "class", recentItem);
                    if (!columnObj) {
                        continue;
                    }

                    items[i].name = columnObj.name;

                    /* if (scope.itemsChooser.containsItem(columnObj.class)) {
                        scope.recentItemsList.push({ 'class': columnObj.class, 'name': columnObj.name });
                    } */
                }

                items.sort(function (x, y) {
                    if (x.weight < y.weight) {
                        return -1;
                    }
                    if (x.weight > y.weight) {
                        return 1;
                    }
                    return 0;
                }).reverse();

                items = items.filter(function (item) {
                    return (allItemsClasses.indexOf(item.class) >= 0);
                });

                items = items.slice(0, 20);

                scope.recentItemsList = items;
            }

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

            scope.instance.clearSelection = function () {
                scope.itemsChooser.clearSelection();
            }

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

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

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

            scope.instance.show = function () {
                if (!scope.recentItemsList.length) {      //sometimes recent items are not loaded yet because of chosen delayed init
                    scope.instance.loadRecentItems();
                }

                showPopup('#' + scope.popupId, function () {
                    // $('#' + scope.popupId).find(".chosen-search-input").focus();

                    $timeout(function () {
                        if (tagCloudInited) {
                            $('#' + scope.popupId).find(".recent-cloud").jQCloud("destroy");
                        }

                        var cloudColours = ["#000000", "#444444", "#666666", "#888888", "#aaaaaa", "#cccccc", "#aaaaaa", "#bbbbbb", "#cccccc", "#dddddd"];
                        var skin = SkinService.selectedSkin.name;
                        if (skin == 'Dark skin') {
                            cloudColours = cloudColours.reverse();
                        }

                        var wordsForCloud = [];
                        wordsForCloud = JSON.parse(JSON.stringify(scope.recentItemsList));
                        for (var i = 0; i < wordsForCloud.length; i++) {
                            wordsForCloud[i].text = wordsForCloud[i].name;
                        }

                        $('#' + scope.popupId).find(".recent-cloud").jQCloud(wordsForCloud, {
                            autoResize: true,
                            steps: 5,
                            // colors: cloudColours,
                            fontSize: {
                                from: 0.06,
                                to: 0.030
                            }
                        });

                        tagCloudInited = true;
                    }, 0, false);
                });
            }

            scope.cloudWordsClicked = function (event) {
                event.stopPropagation();
                if (event.target.classList.contains("jqcloud-word")) {
                    var itemText = event.target.innerText;
                    for (let i = 0; i < scope.recentItemsList.length; i++) {
                        if (scope.recentItemsList[i].name == itemText) {
                            scope.onAddRecentItem(scope.recentItemsList[i].class);
                            return;
                        }
                    }

                }
            }

            scope.instance.hide = function () {
                hidePopup('#' + scope.popupId);
            }

            scope.onAddRecentItem = function (item) {
                if (!scope.itemsChooser.selectItem(item.trim())) {
                    $rootScope.showError(L.tsq("Item '%s' not found", [item]));
                }
            }

            scope.onAddItems = function () {
                if (scope.onAdd({ selectedItems: scope.instance.getSelectedItems() })) {
                    scope.instance.hide();
                }
            }

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

            scope.popupId = UniqueIdGenerator.generateId();
            scope.itemsChooser = {};

            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 items');
            scope.title = scope.title || L.tsq('Add items');
            scope.chooserLabel = scope.chooserLabel || L.tsq('Choose items to add');

            scope.recentItemsList = [];

            scope.onItemsChooserInit = function () {
                if (scope.recentItems) {
                    scope.instance.loadRecentItems();
                    if (scope.instance.afterInit) scope.instance.afterInit();
                    if (scope.afterInit) scope.afterInit();
                }
            }

        }
    };
});