require(['jquery', 'xwiki-meta'], function ($, xm) {
  'use strict';

  /**
   * Handle the notification email interval.
   */
  $(document).off('change.notificationEmailInterval');
  $(document).on('change.notificationEmailInterval', '.notificationEmailInterval', function() {
    var intervalSelect = $(this);
    var notification = new XWiki.widgets.Notification("Your settings are being saved...", 'inprogress');
    var serviceURL = new XWiki.Document(XWiki.Model.resolve('XWiki.Notifications.Code.NotificationPreferenceService',
      XWiki.EntityType.DOCUMENT)).getURL('get', 'outputSyntax=plain');
    var target = $('.notifEmailPreferences').attr('data-target');
    var targetUser = target === 'user' ? $('.notifEmailPreferences').attr('data-user') : '';
    $.post(serviceURL, {
      'action': 'setInterval',
      'interval': intervalSelect.val(),
      'target': target,
      'user': targetUser,
      'csrf': xm.form_token
    }).then(data => {
      notification.replace(new XWiki.widgets.Notification("Saved!", 'done'));
    }).catch(() => {
      notification.replace(new XWiki.widgets.Notification("Failed to save your settings", 'error'));
    });
  });

  /**
   * Handle the include diff in email setting
   */
  $(document).off('change.notificationEmailDiffType');
  $(document).on('change.notificationEmailDiffType', '.notificationEmailDiffType', function() {
    var diffTypeSelect = $(this);
    var notification = new XWiki.widgets.Notification("Your settings are being saved...", 'inprogress');
    var serviceURL = new XWiki.Document(XWiki.Model.resolve('XWiki.Notifications.Code.NotificationPreferenceService',
      XWiki.EntityType.DOCUMENT)).getURL('get', 'outputSyntax=plain');
    var target = $('.notifEmailPreferences').attr('data-target');
    var targetUser = target === 'user' ? $('.notifEmailPreferences').attr('data-user') : '';
    $.post(serviceURL, {
      'action': 'setDiffType',
      'diffType': diffTypeSelect.val(),
      'target': target,
      'user': targetUser,
      'csrf': xm.form_token
    }).then(data => {
      notification.replace(new XWiki.widgets.Notification("Saved!", 'done'));
    }).catch(() => {
      notification.replace(new XWiki.widgets.Notification("Failed to save your settings", 'error'));
    });
  });
});
