(function() {
    'use strict';

    dashboard.categories = dashboard.categories || {};

    dashboard.categories.data = [
        { title: 'jQuery conference' },
        { title: 'js conference' },
        { title: 'css conference' },
        { title: 'packt jquery' }
    ];

    dashboard.categories.init = function() {
        var $categoriesSelector = dashboard.$container.find('#categoriesSelector');
        var $categories = dashboard.$container.find('.dashboardCategoriesList');
        
        var optionTemplate = _.template('<option value="<%= value %>"><%- title %></option>');
        var optionsHtmlArray = _.map(dashboard.categories.data, function(categoryInfo, i) {
            return optionTemplate({
                value: i,
                title: categoryInfo.title
            });
        });
        $categoriesSelector.append(optionsHtmlArray.join(''));


        for (var i = 0; i < dashboard.categories.data.length; i++) {
            var $section = $('<section class="dashboardCategory">Ładowanie...</section>');
            if (i > 0) {
                $section.addClass('hidden');
            }
            $section.appendTo($categories);
            var categoryInfo = dashboard.categories.data[i];
            dashboard.categories.createCategoryButtons($section, categoryInfo);
        }

        $categoriesSelector.change(function() {
            var $selector = $(this);
            var categoryIndex = +$selector.val();
            dashboard.categories.selectCategory(categoryIndex);
        });

        dashboard.$container.find('.dashboardCategories').on('click', 'button', function() {
            var $button = $(this);
            var itemName = $button.text();
            dashboard.informationBox.openNew(itemName);
        });
    };

    dashboard.categories.createCategoryButtons = function($buttonContainer, categoryInfo) {
        dashboard.videoService.searchVideos(categoryInfo.title).then(function(result) {
            categoryInfo.items = result.items;

            var buttonTemplate = _.template('<button><%- title %></button>');
            var buttons = _.map(result.items, function(item) {
                return buttonTemplate({
                    title: item.snippet.title
                });
            });

            $buttonContainer.empty().append(buttons.join(''));
        }).fail(function() {
            $buttonContainer.html('Wystąpił błąd!');
        });
    };

    dashboard.categories.selectCategory = function(categoryIndex) {
        var $dashboardCategories = dashboard.$container.find('.dashboardCategory');
        var $selectedItem = $dashboardCategories.eq(categoryIndex).show();
        $dashboardCategories.not($selectedItem).hide();
    };

})();
