define([
    'aui',
    'jquery',
    'test-helper',
    'bitbucket/internal/feature/commit/difftree/difftree-search-input',
    'bitbucket/internal/util/function'
], function (
    AJS,
    $,
    testHelper,
    DiffTreeSearchInput,
    fn
) {
    'use strict';

    testHelper.setTemplates({
        'bitbucket.internal.feature.difftree.searchInput': '<div id="fixture"><input type="text" /><a href="#" class="delete-button"></a>'
    });

    var testSearchString = 'this is a test search';

    module('difftree-search-input', {
        setup: function() {
            this.searchInput = new DiffTreeSearchInput();
            $('#qunit-fixture').append(this.searchInput.$el);

            this.stream = this.searchInput.getInputs();
            this.stream.onValue($.noop); // bacon stream needs a listener

            this.$formInput = this.searchInput.$el.find('input');

            // set formInputFocused as an internal state (@this is the qunit text context)
            this.$formInput.on('focus', fn.thisToParam(fn.set('formInputFocused', true)).bind(this));
            this.$formInput.on('blur',  fn.thisToParam(fn.set('formInputFocused', false)).bind(this));
        },
        teardown: function() {
            this.searchInput = null;
            this.stream = null;
        }
    });

    test('Enter key behaviour', function() {
        // focus the input
        this.$formInput.focus();
        ok(this.formInputFocused === true, 'Search field is focused');

        // Test that an enter press blurs the field and sends a value to the stream
        this.stream.onValue(function(val) {
            equal(val, testSearchString, "The search string is passed to the stream");
        });

        this.$formInput.val(testSearchString);

        var kbdEvent = $.Event('keyup');
        kbdEvent.keyCode = AJS.keyCode.ENTER;
        this.$formInput.trigger(kbdEvent);

        ok(this.formInputFocused === false, 'Search field is blurred after ENTER was pressed');

    });

    test('Escape key behaviour', function() {
        // focus the input
        this.$formInput.focus();
        ok(this.formInputFocused === true, 'Search field is focused');

        // Test that an escape press blurs the field and *doesn't* send a value to the stream
        this.stream.onValue(function(val) {
            ok(false, 'Should not receive a value in the stream when ESCAPE is pressed');
        });

        this.$formInput.val(testSearchString);

        var kbdEvent = $.Event('keyup');
        kbdEvent.keyCode = AJS.keyCode.ESCAPE;
        this.$formInput.trigger(kbdEvent);

        ok(this.formInputFocused === false, 'Search field is blurred after ESCAPE was pressed');
        equal(this.$formInput.val(), testSearchString, 'Search field value remains unchanged');
    });

});

