(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.CommentDialog = function(app, options) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var $screen = null;
    var $content = null;
    var recordingId;
    var entityType = options.entity_type;
    var sessionId = options.session_id;
    var recordingId = options.recording_id;
    var claimedRecordingId = options.claimed_recording_id;

    function beforeShow(data) {
    }

    function afterShow(data) {
      $("#txtComment", $screen).val('');
      renderComments();
    }

    function afterHide() {
    }

    function renderComments() {
      $content.empty();

      var h1Text = $('h1', $screen).html('comment on this ' + entityType);

      if (entityType === 'session') {
        rest.getSessionHistory(sessionId)
          .done(function(response) {
            if (response && response.comments) {
              $.each(response.comments, function(index, val) {
                renderComment(val.comment, val.creator.id, val.creator.name, 
                  context.JK.resolveAvatarUrl(val.creator.photo_url), $.timeago(val.created_at), val.creator.musician, true);
              });
              context.JK.bindHoverEvents($content);
              context.JK.bindProfileClickEvents($content, ['comment-dialog']);
            }
          })
          .fail(function(xhr) {

          });
      }
      else if (entityType === 'recording') {
        rest.getClaimedRecording(claimedRecordingId)
          .done(function(response) {
            if (response.recording && response.recording.comments) {
              $.each(response.recording.comments, function(index, val) {
                renderComment(val.comment, val.creator.id, val.creator.name, 
                  context.JK.resolveAvatarUrl(val.creator.photo_url), $.timeago(val.created_at), val.creator.musician, true);
              });

              context.JK.bindHoverEvents($content);
              context.JK.bindProfileClickEvents($content, ['comment-dialog']);
            }
          })
          .fail(function(xhr) {

          });
      }
    }

    function renderComment(comment, userId, userName, userAvatarUrl, timeago, musician, append) {

      var options = {
        avatar_url: userAvatarUrl,
        user_id: userId,
        hoverAction: musician ? "musician" : "fan",
        name: userName,
        comment: context._.unescape(comment),
        timeago: timeago
      };

      var $comment = $(context._.template($('#template-comments').html(), options, {variable: 'data'}));
      if (append) {
        $content.append($comment);
      }
      else {
        $content.prepend($comment);
      }
    }

    function addComment() {
      var comment = $("#txtComment", $screen).val();
      if ($.trim(comment).length > 0) {
        if (entityType === 'session') {
          rest.addSessionComment(sessionId, JK.currentUserId, comment)
            .done(function(response) {
              // $("#spnCommentCount").html(parseInt($("#spnCommentCount").text()) + 1);
              renderComment(comment, context.JK.currentUserId, context.JK.currentUserName,
                context.JK.currentUserAvatarUrl, $.timeago(Date.now()), context.JK.currentUserMusician, false);
            })
            .fail(function(jqXHR) {
              logger.error("unable to add recording comment: " + jqXHR.responseText)
              app.notify({text: 'unable to add comment, please try again later.'})
            })
        }
        else if (entityType === 'recording') {
          logger.debug("recording comment logged! " + comment)
          rest.addRecordingComment(recordingId, JK.currentUserId, comment)
            .done(function(response) {
              // $("#spnCommentCount", $scope).html(parseInt($("#spnCommentCount").text()) + 1);
              renderComment(comment, context.JK.currentUserId, context.JK.currentUserName, 
                context.JK.currentUserAvatarUrl, $.timeago(Date.now()), context.JK.currentUserMusician, false);
            })
            .fail(function(jqXHR) {
              logger.error("unable to add recording comment: " + jqXHR.responseText)
              app.notify({text: 'unable to add comment, please try again later.'})
            })
        }
      }
    }

    function events() {
      var $btnSelector = $('#btn-add-comment', $screen);
      var $txtComment = $('#txtComment', $screen);

      if (!context.JK.currentUserId) {
        $txtComment.attr('placeholder', 'You must be logged in to add a comment.');
        $btnSelector.removeClass('button-orange');
        $btnSelector.addClass('button-grey');
      }
      else {
        $btnSelector.unbind('click');
        $btnSelector.click(addComment);
      }
    }

    function showDialog() {
      return app.layout.showDialog('comment-dialog');
    }

    function initialize() {

      var dialogBindings = {
        'beforeShow' : beforeShow,
        'afterShow' : afterShow,
        'afterHide': afterHide
      };

      app.bindDialog('comment-dialog', dialogBindings);

      $screen = $('[layout-id="comment-dialog"]');
      $content = $screen.find('.dialog-comment-scroller');

      events();
    }

    this.initialize = initialize;
    this.showDialog = showDialog;
  }

  return this;
})(window,jQuery);