(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.AcceptFriendRequestDialog = function(app) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var $dialog = null;
    var $dialogContents = null;
    var $notFriendsTemplate = null;
    var $alreadyFriendsTemplate = null;
    var $genericErrorTemplate = null;
    var $alreadyProcessedTemplate = null;
    var $acceptBtn = null;
    var $closeBtn = null;
    var $cancelBtn = null;
    var $actionBtns = null;
    var friendRequestId = null;
    var user = null;
    var sending = false;
    var friendRequest = null;
    var sidebar = null;

    function reset() {
      sending = false;
      friendRequest = null;
      $dialogContents.empty();
      $actionBtns.hide();
      $actionBtns.find('a').hide();
      $acceptBtn.text('ACCEPT');
    }

    function buildShowRequest() {
      return {friend_request_id: friendRequestId};
    }

    function buildAcceptRequest() {
      var message = {};

      message['friend_request_id'] = friendRequest.id;
      message['status'] = 'accept';

      return message;
    }

    function acceptRequest(e) {

      if(!sending) {
        sending = true;

        $acceptBtn.text('ACCEPTING...')

        rest.acceptFriendRequest(buildAcceptRequest())
        .done(function() {
            app.layout.closeDialog('accept-friend-request')
            sidebar.refreshFriends();
        })
        .fail(function(jqXHR) {
          app.notifyServerError(jqXHR, 'Unable to Accept Friend Request');
        })
        .always(function() {
          sending = false;
          $acceptBtn.text('ACCEPT');
        })

      }
      return false;
    }


    function modifyResponseWithUIData() {
      friendRequest.friend.user_type = friendRequest.friend.musician ? 'musician' : 'fan'
      friendRequest.user.user_type = friendRequest.user.musician ? 'musician' : 'fan'
      friendRequest.friend.photo_url = context.JK.resolveAvatarUrl(friendRequest.friend.photo_url);
      friendRequest.user.photo_url = context.JK.resolveAvatarUrl(friendRequest.user.photo_url);
    }

    function renderNoActionPossibleBtns() {
      $closeBtn.show();
      $actionBtns.show();
    }

    function renderDefaultBtns() {
      $cancelBtn.show();
      $acceptBtn.show();
      $actionBtns.show();
    }
    function renderAlreadyFriends(options) {
      return $(context._.template($alreadyFriendsTemplate.html(), options, { variable: 'data' }));
    }

    function renderAlreadyProcessed(options) {
      return $(context._.template($alreadyProcessedTemplate.html(), options, { variable: 'data' }));
    }

    function renderNotFriends(options) {
      return $(context._.template($notFriendsTemplate.html(), options, { variable: 'data' }));
    }

    function renderGenericError(options) {
      return $(context._.template($genericErrorTemplate.html(), options, { variable: 'data' }));
    }

    function beforeShow(args) {

      app.layout.closeDialog('accept-friend-request') // ensure no others are showing. this is a singleton dialog

      app.user()
        .done(function(userDetail) {
          user = userDetail;

          friendRequestId = args.d1;

          if(!friendRequestId) throw "friend request must be specified in AcceptFriendRequestDialog"

          rest.getFriendRequest(buildShowRequest())
            .done(function(response) {
              friendRequest = response;
              modifyResponseWithUIData();
              var options = friendRequest;

              var contents = null;

              if(friendRequest.user_id == user.id) {
                contents = renderGenericError({error_message: 'You can\'t become friends with yourself.'})
                renderNoActionPossibleBtns();
              }
              else if(friendRequest.user.is_friend) {
                // already friends
                contents = renderAlreadyFriends(options);
                renderNoActionPossibleBtns();
              }
              else if(friendRequest.status) {
                contents = renderAlreadyProcessed(options);
                renderNoActionPossibleBtns();
              }
              else {
                contents = renderNotFriends(options);
                renderDefaultBtns();
              }

              $dialogContents.append(contents);
              context.JK.bindHoverEvents(contents);
            })
            .fail(function(jqXHR) {
              if(jqXHR.status == 403) {
                var contents = renderGenericError({error_message: 'You do not have permission to access this information.'})
                $dialogContents.append(contents);
                context.JK.bindHoverEvents(contents);
              }
              else if(jqXHR.status == 404) {
                var contents = renderGenericError({error_message: 'This friend request no longer exists.'})
                $dialogContents.append(contents);
                context.JK.bindHoverEvents(contents);
              }
              else {
                app.notifyServerError(jqXHR, 'Unable to Load Friend Request');
              }
              renderNoActionPossibleBtns();
            })
        })
      .fail(function() {
            // not logged in :(
            var redirectPath= '?redirect-to=' + encodeURIComponent(JK.locationPath());
            window.location.href = '/signin' + redirectPath;
            return
          })
    }

    function events() {
      $acceptBtn.click(acceptRequest);
    }

    function afterHide() {
      reset();
    }

    function initialize(sidebarInstance) {
      var dialogBindings = {
        'beforeShow' : beforeShow,
        'afterHide': afterHide
      };


      app.bindDialog('accept-friend-request', dialogBindings);

      sidebar = sidebarInstance;
      $dialog = $('#accept-friend-request-dialog');
      $dialogContents = $dialog.find('.dialog-inner');
      $notFriendsTemplate = $('#template-friend-request-not-friends');
      $alreadyFriendsTemplate = $('#template-friend-request-already-friends');
      $alreadyProcessedTemplate = $('#template-friend-request-already-processed')
      $genericErrorTemplate = $('#template-friend-generic-error');
      $acceptBtn = $dialog.find('.btn-accept-friend-request');
      $cancelBtn = $dialog.find('.btn-cancel-dialog');
      $closeBtn = $dialog.find('.btn-close-dialog');
      $actionBtns = $dialog.find('.action-buttons');

      events();
    }

    this.initialize = initialize;
  }

  return this;
})(window,jQuery);
