/// <reference path="../../references.js" />

rwthapp.util.initNamespace("templates.das");

rwthapp.templates.das.channelOverview = {
    load: function (template, parameters) {

        return rwthapp.connection.api.das.getChannelList().then(function (data) {
            // TODO assume sorted list?

            // Create list of channels based on first letter of the channel name
            var channelList = [];
            var currentLetter = "";
            for (var i = 0; i < data.length; i++) {
                var firstLetter = data[i].channelName[0].toUpperCase();
                if (firstLetter !== currentLetter) {
                    currentLetter = firstLetter;
                    channelList.push({
                        firstLetter: firstLetter,
                        channels: []
                    });
                }

                channelList[channelList.length - 1].channels.push(data[i]);
            }

            return {
                template: template,
                parameters: {
                    channelList: channelList
                },
                title: rwthapp.localization.getLocalizedString("titles.channelOverview"),
                subTitle: rwthapp.localization.getLocalizedString("subTitles.channelOverview")
            };
        });
    },
    ready: function () {
        // Channel filter
        $('#filterInput').on("input", function () {
            var filter = $('#filterInput').val().toLowerCase(); // Filtering is done case-insensitive

            // Hide all channels which do not match filter 
            $("#channelList .das-list-item").each(function (index, element) {
                if ($(element).find(".firstline").html().toLowerCase().indexOf(filter) > -1) {
                    $(element).show();
                } else {
                    $(element).hide();
                }
            });

            // Hide all headers which do not have visible items
            $("#channelList .das-list-header").each(function (index, element) {
                if ($(element).next(".das-list-container").children(".das-list-item:visible").length > 0) {
                    $(element).show();
                } else {
                    $(element).hide();
                }
            });
        });
    },
    exit: function () {
        $('#filterInput').off("input");
    }
};