(function(context, $) {

  "use strict";

  context.JK = context.JK || {};

  context.JK.ShowSessionInfo = function(app, musicSessionId) {
    var EVENTS = context.JK.EVENTS;
    var logger = context.JK.logger;
    var rest = JK.Rest();
    var ui = new context.JK.UIHelper(app);
    var sessionUtils = context.JK.SessionUtils;
    var helpBubble = context.JK.HelpBubbleHelper;
    var $btnAction = $("#btn-action");
    var $templateLatencyDetail = null;
    var $landingSidebar = null;

    function addComment() {
      var comment = $("#txtSessionInfoComment").val();
      if ($.trim(comment).length > 0) {
        rest.addSessionInfoComment(musicSessionId, comment)
          .done(function(response) {
            renderComment(comment, context.JK.currentUserId, context.JK.currentUserName,
              context.JK.currentUserAvatarUrl, $.timeago(Date.now()), false);

            $("#txtSessionInfoComment").val('');
          });
      }
    }

    function renderComment(comment, userId, userName, userAvatarUrl, timeago, append) {
      var template = $('#template-landing-comment').html();
      var commentHtml = context.JK.fillTemplate(template, {
        avatar_url: userAvatarUrl,
        user_id: userId,
        hoverAction: "musician",
        name: userName,
        comment: context._.unescape(comment),
        timeago: timeago
      });

      if (append) {
        $(".landing-comment-scroller").append(commentHtml);
      }
      else {
        $(".landing-comment-scroller").prepend(commentHtml);
      }

      context.JK.bindProfileClickEvents();
      context.JK.bindHoverEvents($(".landing-comment-scroller"));
    }

    function registerScheduledSessionComment() {
      context.JK.JamServer.registerMessageCallback(context.JK.MessageType.SCHEDULED_SESSION_COMMENT, function(header, payload) {
        logger.debug("Handling SCHEDULED_SESSION_COMMENT msg " + JSON.stringify(payload));
        app.notify({
          "title": "Session Comment",
          "text": payload.msg,
          "icon_url": context.JK.resolveAvatarUrl(payload.photo_url)
        });
      });
    }

    // this is done post-page load to allow websocket connection to be established
    function addLatencyDetails(session) {
        if (session.approved_rsvps && session.approved_rsvps.length > 0) {
          // loop through each record in RSVPs, which has already been rendered, and extract
          // the user ID
          $('.rsvp-details').each(function(index) {
            var $user = $(this).find('div[hoveraction="musician"]');
            var userId = $user.attr('user-id');

            var user = null;

            for (var i=0; i < session.approved_rsvps.length; i++) {
              if (session.approved_rsvps[i].id === userId) {
                user = session.approved_rsvps[i];
                break;
              }
            }

            if(user) {
              // add the latency details for this user to the UI
              var $latencyHtml = $(context.JK.fillTemplate($templateLatencyDetail.html(),
                sessionUtils.createLatency(user)));
              var $latencyBadge = $latencyHtml.find('.latency');
              app.user().done(function(userMe) {
                helpBubble.scoreBreakdown($latencyBadge, context.JK.currentUserId == user.id, user.full_score, userMe.last_jam_audio_latency, user.audio_latency, user.internet_score, {offsetParent: $landingSidebar});
              })
              $(this).find('.latency-tags').append($latencyHtml);
            }
            else {
              logger.warn("unable to find user in approved_rsvps");
            }
          });
        }
    }

    function initialize() {
      registerScheduledSessionComment();

      $landingSidebar = $('.landing-sidebar');
      $templateLatencyDetail = $('#template-latency-detail');

      context.JK.bindHoverEvents($landingSidebar);
      context.JK.setInstrumentAssetPath($('.instrument-icon', $landingSidebar));

      // render comments
      $(".landing-comment-scroller").empty();
      rest.getSessionHistory(musicSessionId)
        .done(function(response) {
          if (response && response.session_info_comments) {
            $.each(response.session_info_comments, function(index, val) {
              renderComment(val.comment, val.creator.id, val.creator.name, 
                context.JK.resolveAvatarUrl(val.creator.photo_url), $.timeago(val.created_at), true);
            });
          }

          addLatencyDetails(response);
        })
        .fail(function(xhr) {

        });

      // retrieve RSVP requests for this user to determine which CTA to display
      rest.getRsvpRequests(musicSessionId)
        .done(function(rsvps) {
          if (rsvps && rsvps.length > 0) {
            // the first RSVP should be the most recent (users may have many RSVPs to same session if they cancel
            // and resubmit); use its status to determine what CTA to present
            var rsvp = rsvps[0];
            if (rsvp.canceled) {
              $('.call-to-action').html("Tell the session organizer you'd like to play in this session");
              $btnAction.html('RSVP NOW!');
              $btnAction.click(function(e) {
                ui.launchRsvpSubmitDialog(musicSessionId)
                  .one(EVENTS.RSVP_SUBMITTED, function() {
                    location.reload();
                  })
              });
            }
            else {
              var declined = true;
              if (rsvp.rsvp_requests_rsvp_slots) {
                for (var x=0; x < rsvp.rsvp_requests_rsvp_slots.length; x++) {
                  if (rsvp.rsvp_requests_rsvp_slots[x].chosen || rsvp.rsvp_requests_rsvp_slots[x].chosen == null) {
                    declined = false;
                  }
                }
              }

              if (declined) {
                $('.call-to-action').html('Your RSVP request to this session has been declined.');
                $btnAction.hide();
              }
              else {
                $('.call-to-action').html('Tell the session organizer if you can no longer join this session');
                $btnAction.html('CANCEL RSVP');
                $btnAction.click(function(e) {
                  ui.launchRsvpCancelDialog(musicSessionId, rsvp.id)
                    .one(EVENTS.RSVP_CANCELED, function() {
                      location.reload();
                    });
                });
              }
            }
          }
          // no RSVP
          else {
            $('.call-to-action').html("Tell the session organizer you'd like to play in this session");
            $btnAction.html('RSVP NOW!');
            $btnAction.click(function(e) {
              ui.launchRsvpSubmitDialog(musicSessionId)
                .one(EVENTS.RSVP_SUBMITTED, function() {
                  location.reload();
                })
            });
          }
        })
        .fail(function(xhr) {

        });

      $("#btnPostComment").click(function(e) {
        if ($.trim($("#txtSessionInfoComment").val()).length > 0) {
          addComment();
          $("#txtSessionComment").val('');
          $("#txtSessionComment").blur();
        }
      });
    }
    
    this.initialize = initialize;
  }

})(window, jQuery);