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

    var $ = jQuery;
    var $webcamCapture;

    module('widget-webcam-capture', {
        setup: function() {
            $webcamCapture = $(bitbucket.internal.widget.webcamCapture());
            $('#qunit-fixture').append($webcamCapture);
        },
        teardown: function() {
            $('#qunit-fixture').empty();
        }
    });

    test('No access to webcam', function() {
        navigator.getUserMedia = function(settings, successCallback, errorCallback) {
            errorCallback();
        };

        var WebcamCapture = require('bitbucket/internal/widget/webcam-capture');
        var webcamCapture = new WebcamCapture($webcamCapture);

        webcamCapture.start();
        ok(!$webcamCapture.find('.no-access').hasClass('hidden'));
        ok($webcamCapture.find('.grant-access').hasClass('hidden'));
    });

    asyncTest('Capturing to canvas', function() {
        expect(2);

        var moustash = require('bitbucket/internal/feature/moustash');
        sinon.spy(moustash, 'addToFaces');
        var WebcamCapture = require('bitbucket/internal/widget/webcam-capture');
        var captured = $.Deferred();

        var webcamCapture = new WebcamCapture($webcamCapture, {
            width: 200,
            onCapture: captured.resolve.bind(captured)
        });
        setTimeout(captured.reject.bind(captured), 5000);

        captured.always(start).done(function(url) {
            ok(url, 'Captured callback is called with dataUrl');
            ok(moustash.addToFaces.calledOnce);
        }).fail(function() {
            ok(false, 'Webcam capture took too long and was aborted');
        });

        // Webcam capture is supposed to write the video to canvas but that requires a stream.
        // For the test, use an image
        var image = webcamCapture.video = new Image();
        var imagePromise = $.Deferred();
        image.onload = function() {
            imagePromise.resolve();
        };
        var loadResourcesPromise = require('bitbucket/internal/feature/moustash').loadResources();

        $.when(loadResourcesPromise, imagePromise).done(function() {
            webcamCapture._capture(true);
        });
        image.src = AJS.contextPath() + '/s/1/_/download/resources/com.atlassian.bitbucket.server.bitbucket-web:avatar/avatar/default-avatar-128.png';
    });
});