define([
    'aui',
    'jquery',
    'bitbucket/internal/util/shortcuts'
], function(
    AJS,
    $,
    shortcutsUtil
) {

    'use strict';

    QUnit.module('util-shortcuts', {
        setup: function() {
            this.boundCallBacks = [];
        },
        teardown: function() {
            this.boundCallBacks.forEach(function (callback) {
                callback();
            });
        },
        bind: function(name, callback) {
            this.boundCallBacks.push(shortcutsUtil.bind(name, callback));
        }
    });

    QUnit.test('testLazyShortcut', function(assert) {
        register('test1', 'a');
        var callbackTest1 = sinon.spy();
        this.bind('test1', callbackTest1);

        fakeKeyPress('a');

        var callbackTest2 = sinon.spy();
        this.bind('test2', callbackTest2);
        register('test2', 'b');

        fakeKeyPress('b');

        assert.equal(callbackTest1.callCount, 1);
        assert.equal(callbackTest2.callCount, 1);
    });

    QUnit.test('testLazyGetsUnbound', function(assert) {
        var keys = 'a';
        var callback1 = sinon.spy();
        var callback2 = sinon.spy();
        var whenIType = AJS.whenIType(keys);
        whenIType.execute(callback1);

        shortcutsUtil.registerLazy('test1', whenIType, keys);
        this.bind('test1', callback2);

        fakeKeyPress('a');

        assert.equal(callback1.callCount, 0);
        assert.equal(callback2.callCount, 1);
    });

    QUnit.test('testLazyEventPreventDefault', function(assert) {
        register('test1', 'a');
        var callback = sinon.spy();
        var unbind = shortcutsUtil.bind('test1', callback);

        var event = fakeKeyPress('a');
        assert.ok(event.isDefaultPrevented());

        unbind();

        event = fakeKeyPress('a');
        assert.ok(!event.isDefaultPrevented());

        assert.equal(callback.callCount, 1);
    });

    function fakeKeyPress(key) {
        var event = $.Event('keypress');
        event.which = key.charCodeAt(0);
        $(document).trigger(event);
        return event;
    }

    function register(name, keys) {
        shortcutsUtil.registerLazy(name, AJS.whenIType(keys), keys);
    }

});