(function(context,$) {

    "use strict";

    context.JK = context.JK || {};
    context.JK.SessionList = function(app) {
        var logger = context.JK.logger;
        var termsDialog;
        var LATENCY = {
            GOOD : {description: "GOOD", style: "latency-green", min: 0.0, max: 20.0},
            MEDIUM : {description: "MEDIUM", style: "latency-yellow", min: 20.0, max: 40.0},
            POOR : {description: "POOR", style: "latency-red", min: 40.0, max: 10000000000.0},
            UNREACHABLE: {description: "UNREACHABLE", style: "latency-grey", min: -1, max: -1}
        };

        var AUDIENCE = {
            OPEN_TO_FANS: "Open to Fans",
            MUSICIANS_ONLY:"Musicians Only"
        };

        var instrument_logo_map = context.JK.getInstrumentIconMap24();

        /**
        * Render a single session line into the table.
        * It will be inserted at the appropriate place according to the
        * sortScore in sessionLatency.
        */
        function renderSession(session, sessionLatency, tbGroup, rowTemplate, musicianTemplate, onMusiciansComplete) {
            // latency
            var latencyInfo = sessionLatency.sessionInfo(session.id);
            var latencyDescription = "";
            var latencyStyle = "";
            var gearLatency = context.jamClient.SessionGetDeviceLatency();
            var showJoinLink = true;

            var totalLatency = (latencyInfo.averageLatency / 2) + gearLatency;

            logger.debug("latencyInfo.averageLatency=" + latencyInfo.averageLatency);
            logger.debug("gearLatency=" + gearLatency);

            if (latencyInfo.averageLatency === -1) {
                latencyDescription = LATENCY.UNREACHABLE.description;
                latencyStyle = LATENCY.UNREACHABLE.style;
                showJoinLink = false;
            }
            else {
                if (totalLatency <= LATENCY.GOOD.max) {
                    latencyDescription = LATENCY.GOOD.description;
                    latencyStyle = LATENCY.GOOD.style;
                }
                else if (totalLatency > LATENCY.MEDIUM.min && totalLatency <= LATENCY.MEDIUM.max) {
                    latencyDescription = LATENCY.MEDIUM.description;
                    latencyStyle = LATENCY.MEDIUM.style;
                }
                else {
                    latencyDescription = LATENCY.POOR.description;
                    latencyStyle = LATENCY.POOR.style;
                    showJoinLink = false;
                }
            }

            // audience
            var audience = AUDIENCE.OPEN_TO_FANS;
            if (!(session.fan_access)) {
                audience = AUDIENCE.MUSICIANS_ONLY;
            }

            var i, participant = null;
            var musicians = '';
            var musicianArray = [];
            for (i=0; i < session.participants.length; i++) {
                participant = session.participants[i];

                var instrumentLogoHtml = '';
                var j;

                // loop through the tracks to get the instruments
                for (j=0; j < participant.tracks.length; j++) {
                    var track = participant.tracks[j];
                    logger.debug("Find:Finding instruments. Participant tracks:");
                    logger.debug(participant.tracks);
                    var inst = '../assets/content/icon_instrument_default24.png';
                    if (track.instrument_id in instrument_logo_map) {
                        inst = instrument_logo_map[track.instrument_id];
                    }
                    instrumentLogoHtml += '<img src="' + inst + '" width="24" height="24" />&nbsp;';
                }

                var id = participant.user.id;
                var name = participant.user.name;
                var photoUrl = context.JK.resolveAvatarUrl(participant.user.photo_url);
                var musicianVals = {
                    avatar_url: photoUrl,
                    profile_url: "/#/profile/" + id,
                    musician_name: name,
                    instruments: instrumentLogoHtml
                };

                var musician = {};
                musician.id = id;
                musician.name = name;
                musicianArray[i] = musician;

                var musicianInfo = context.JK.fillTemplate(musicianTemplate, musicianVals);
                musicians += musicianInfo;
            }

            onMusiciansComplete(musicianArray);

            var sessionVals = {
                id: session.id,
                genres: session.genres.join (', '),
                description: session.description || "(No description)",
                musician_template: musicians,
                audience: audience,
                latency_text: latencyDescription,
                latency_style: latencyStyle,
                sortScore: latencyInfo.sortScore,
                play_url: "TODO",
                join_link_display_style: "block" // showJoinLink ? "block" : "none"
            };

            var row = context.JK.fillTemplate(rowTemplate, sessionVals);
            var insertedEarly = false;
            $.each($('tr', tbGroup), function(index, nextRow) {
                var $nextRow = $(nextRow);
                var rowSortScore = parseInt($nextRow.attr('data-sortScore'), 10);
                if (sessionVals.sortScore > rowSortScore) {
                    $nextRow.before(row);
                    insertedEarly = true;
                    return false; // break
                }
            });
            if (!insertedEarly) {
                $(tbGroup).append(row);

                // wire up the Join Link to the T&Cs dialog
                var $parentRow = $('tr[id=' + session.id + ']', tbGroup);
                $('#join-link', $parentRow).click(function(evt) {
                    openTerms(session.id);
                });
            }
        }

        function openTerms(sessionId) {
            termsDialog = new context.JK.TermsDialog(app, sessionId, onTermsAccepted);
            termsDialog.initialize();
            app.layout.showDialog('terms');
        }

        function onTermsAccepted(sessionId) {
            context.location = '#/session/' + sessionId;
        }

        function events() {
        }

        this.renderSession = renderSession;

        return this;
    };

 })(window,jQuery);