/* global AJS:false */
AJS.test.require('com.atlassian.bitbucket.server.bitbucket-web:simple-select', function() {

    var $ = jQuery;
    var SimpleSelect = require('bitbucket/internal/widget/simple-select');
    var selector;
    var onSelectCount;

    module('widget-simple-select', {
        setup: function() {
            onSelectCount = 0;
            var menuId = 'select-menu';
            var triggerId = 'select-trigger';
            $('#qunit-fixture').append(widget.aui.dropdown2({
                menuId: menuId,
                menuContent: '<ul><li id="jira" data-value="jira">JIRA</li><li id="confluence" data-value="confluence">Confluence</li><li id="fecru" data-value="fecru">FECRU</li></ul>',
                triggerId: triggerId
            }));

            selector = new SimpleSelect('#' + triggerId, '#' + menuId, {
                onSelect: function() {
                    onSelectCount++;
                }
            });
        },
        teardown: function() {
            // dropdown menu is outside qunit-fixture so we need to remove it manually
            selector.$menu.remove();
        }
    });

    test('First item is initially selected', function() {
        assertSelectedItem('jira', 'JIRA');
        equal(onSelectCount, 0, 'On select handler should not have been called');
    });

    test('Change selection', function() {
        // change selection via clicking on dropdown
        selector.$trigger.click();
        $('#fecru').click();
        assertSelectedItem('fecru', 'FECRU');
        equal(onSelectCount, 1, 'On select handler should have been called once');
    });

    test('Update list items', function() {
        var $newList = $('<ul><li id="apple" data-value="apple">Apple</li><li data-selected id="banana" data-value="banana">Banana</li><li id="carrot" data-value="carrot">Carrot</li></ul>');
        selector.updateList($newList);
        ok(!$('#fecru').length, 'FECRU should no longer be an item');
        ok($('#apple').length, 'Apple should now be an item');
        assertSelectedItem('banana', 'Banana', 'Sets selected item to item with data-selected attribute');
        equal(onSelectCount, 0, 'On select handler should not have been called');
    });

    function assertSelectedItem(value, name) {
        equal(selector.getSelectedValue(), value, name + ' should be selected');
        equal(selector.$trigger.text(), name, name + ' should be in trigger');
    }
});