require(['jquery', 'xwiki-meta'], function ($, xm) {
  'use strict';
  $(document).ready(function() {
    /**
     * Save the new user status.
     */
    var changeUserStatus = function (action) {
      var notification = new XWiki.widgets.Notification("Saving...", 'inprogress');
      var url = new XWiki.Document(XWiki.Model.resolve('XWiki.Notifications.Code.NotificationPreferenceService', XWiki.EntityType.DOCUMENT)).getURL('get', 'outputSyntax=plain');
      $.post(url, {
        'action': action,
        'csrf': xm.form_token,
        'userId': XWiki.Model.serialize(xm.documentReference)
      }).done(function() {
        notification.hide();
        new XWiki.widgets.Notification("Done", 'done');
        if (action == 'watchUser') {
          $('.notificationWatchUserNotFollowing').addClass('hidden');
          $('.notificationWatchUserFollowing').removeClass('hidden')
        } else {
          $('.notificationWatchUserFollowing').addClass('hidden');
          $('.notificationWatchUserNotFollowing').removeClass('hidden');
        }
      }).fail(function() {
        notification.hide();
        new XWiki.widgets.Notification("Error saving the notification setting", 'error');
      });
    };

    var setUserDisableStatus = function(action) {
      var notification = new XWiki.widgets.Notification("Saving...", 'inprogress');
      var url = new XWiki.Document(XWiki.Model.resolve('XWiki.XWikiUserProfileSheet', XWiki.EntityType.DOCUMENT)).getURL('get', 'outputSyntax=plain');
      $.post(url, {
        'action': action,
        'csrf': xm.form_token,
        'userId': XWiki.Model.serialize(xm.documentReference)
      }).done(function(data) {
        notification.hide();
        if (data.success) {
          new XWiki.widgets.Notification("Done", 'done');
          if (action == 'disable') {
            $('#disable').addClass('hidden');
            $('#enable').removeClass('hidden');
          } else {
            $('#disable').removeClass('hidden');
            $('#enable').addClass('hidden');
          }
        } else {
          new XWiki.widgets.Notification("Error saving the user status", 'error');
        }
      }).fail(function() {
        notification.hide();
        new XWiki.widgets.Notification("Error saving the user status", 'error');
      });
    };

    $('#disable').click(function (event) {
      setUserDisableStatus('disable');
    });

    $('#enable').click(function (event) {
      setUserDisableStatus('enable');
    });

    /**
     * DOM events
     */
    $('.notificationWatchUserAdd').click(function (event) {
      changeUserStatus('watchUser');
    });
    $('.notificationWatchUserRemove').click(function (event) {
      changeUserStatus('unwatchUser');
    });
  });
});
