(function(context,$) {

    "use strict";

    context.JK = context.JK || {};
    context.JK.TestBridgeScreen = function(app) {
        var logger = context.JK.logger;
        var selectors = {
            clientId: '#testBridge-clientid',
            tClientId: '#template-testBridge-clientid',
            cSession: '#testBridge-createSession',
            sessionId: '#testBridge-createdSessionId',
            jSession: '#testBridge-joinSession',
            testLatency: '#testBridge-TestLatency',
            testLatencyResponse: '#testBridge-TestLatencyResponse',
            getDevices: '#testBridge-GetDevices',
            ftue: '#testBridge-GetSetFTUE'
        };

        function afterShow(data) {}

        function loggedIn(header, payload) {
            var clientId = payload.client_id;
            renderClientId(clientId);
        }

        function renderClientId(clientId) {
            var template = $(selectors.tClientId).html();
            var replacements = {
                clientid: clientId
            };
            var html = context.JK.fillTemplate(template, replacements);
            $(selectors.clientId).html(html);
        }

        function createSessionHandler(evt) {
            var prefix = $(selectors.cSession + ' input[type="text"]').val();
            createTestSession(prefix);
        }

        function createTestSession(prefix) {
            var session = {
                client_id: app.clientId,
                description: "Test Session " + prefix,
                genres: ["african"],
                fan_chat: true,
                fan_access: true,
                approval_required: false,
                musician_access: true,
                as_musician: true,
                legal_terms: true,
                tracks: [
                    { instrument_id: "electric guitar", sound: "mono" }
                ]
            };
            var url = "/api/sessions";
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                url: url,
                processData:false,
                data: JSON.stringify(session),
                success: function(response) {
                    var newSessionId = response.id;
                    $(selectors.sessionId).html(newSessionId);
                },
                error: app.ajaxError
            });
        }

        function joinSessionHandler(evt) {
            var sessionId = $(selectors.jSession + ' input[type="text"]').val();
            logger.debug('joinSessionHandler. ID: ' + sessionId);
            context.JK.joinMusicSession(sessionId, app);
        }

        function testLatencyHandler(evt) {
            var clientId = $(selectors.testLatency + ' input[type="text"]').val();
            logger.debug('testBridge Screen: testLatencyHandler: clientId: ' + clientId);
            var jsFunction = "JK.TestBridgeLatencyResponse";
            context.jamClient.TestLatency(clientId, jsFunction);
        }

        function latencyResponse(response) {
            logger.debug("latencyResponse, called from jamClient: " + response);
            var latency = JSON.stringify(response);
            $(selectors.testLatencyResponse).html(latency);
        }

        function getDevicesHandler(evt) {
            var response = context.jamClient.GetASIODevices();
            logger.debug(response);
            $(selectors.getDevices + ' textarea').val(JSON.stringify(response));
        }

        function getFTUEHandler(evt) {
            var response = context.jamClient.GetFTUE();
            logger.debug(response);
            $(selectors.ftue + ' textarea[data-what="GetFTUE"]').val(JSON.stringify(response));
        }

        function setFTUEHandler(evt) {
            var val = Boolean($(selectors.ftue + ' form input[name="ftue"]:checked').val());
            logger.debug('ftue:' + val);
            logger.debug(typeof(val));
            context.jamClient.SetFTUE(val);
        }

        function events() {
            $(selectors.cSession + ' input[type="button"]').click(createSessionHandler);
            $(selectors.jSession + ' input[type="button"]').click(joinSessionHandler);
            $(selectors.testLatency + ' input[type="button"]').click(testLatencyHandler);
            $(selectors.getDevices + ' input[type="button"]').click(getDevicesHandler);
            $(selectors.ftue + ' input[type="button"][value="Get"]').click(getFTUEHandler);
            $(selectors.ftue + ' input[type="button"][value="Set"]').click(setFTUEHandler);
        }

        function initialize() {
            var screenBindings = { 'afterShow': afterShow };
            app.bindScreen('testBridge', screenBindings);
            events();
            context.JK.JamServer.registerMessageCallback(
                context.JK.MessageType.LOGIN_ACK, loggedIn);
        }

        // Public
        this.initialize = initialize;

        context.JK.TestBridgeLatencyResponse = latencyResponse;

    };

 })(window,jQuery);