require(['jquery', 'xwiki-meta'], function ($, xm) {
  'use strict';
  
   $(function() {
    /** Add autocomplete attributes to ease form filling. */
    var fieldsPurposes = [
        {
          'name': 'first_name',
          'purpose': 'given-name'
        },
        {
          'name': 'last_name',
          'purpose': 'family-name'
        },
        {
          'name': 'company',
          'purpose': 'organization'
        },
        {
          'name': 'email',
          'purpose': 'email'
        },
        {
          'name': 'phone',
          'purpose': 'tel'
        },
        {
          'name': 'address',
          'purpose': 'street-address'
        },
        {
          'name': 'blog',
          'purpose': 'url'
        }
      ];
    fieldsPurposes.forEach(function (entry) {
      var inputField = $('[name$="' + entry.name + '"]');
      if (inputField.length === 1) {
        inputField.attr('autocomplete', entry.purpose);
      }
    });

    /**
     * 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,
        'user': XWiki.Model.serialize(xm.documentReference),
        'target': 'user'
      }).then(() => {
        notification.hide();
        new XWiki.widgets.Notification("Done", 'done');
        if (action == 'watchUser') {
          $('.notificationWatchUserNotFollowing').addClass('hidden');
          $('.notificationWatchUserFollowing').removeClass('hidden')
        } else {
          $('.notificationWatchUserFollowing').addClass('hidden');
          $('.notificationWatchUserNotFollowing').removeClass('hidden');
        }
      }).catch(() => {
        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)
      }).then(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');
        }
      }).catch(() => {
        notification.hide();
        new XWiki.widgets.Notification("Error saving the user status", 'error');
      });
    };

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

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

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