require(['jquery', 'xwiki-meta'], function ($, xm) {
  var likeUIXReference = XWiki.Model.resolve('XWiki.Like.LikeUIX', XWiki.EntityType.DOCUMENT);
  var likeUIXurl = new XWiki.Document(likeUIXReference).getURL('get');
  
  var likeClick = function () {
    var isLiked = $('#is-liked').val() == "true";
    if (!isLiked) {
      triggerLike();
    } else {
      triggerUnlike();
    }
  };

  var triggerLike = function () {
     var likeButton = $('.like-button').first();
     $.post(likeUIXurl, {
        'xaction': 'like',
        'form_token': xm.form_token,
        'document': XWiki.Model.serialize(xm.documentReference)
     }).then(data => {
       likeButton.removeClass('btn-primary');
       likeButton.addClass('btn-default');
       likeButton.find('.like-number').text(data.counter);
       $('#is-liked').val('true');
       new XWiki.widgets.Notification("The page has been liked.", 'done');
     }).catch(() => {
       new XWiki.widgets.Notification("Error when trying to like the page.", 'error');
     });
  };

  var triggerUnlike = function () {
    var unlikeButton = $('.like-button').first();
    $.post(likeUIXurl, {
      'xaction': 'unlike',
      'form_token': xm.form_token,
      'document': XWiki.Model.serialize(xm.documentReference)
    }).then(data => {
      unlikeButton.removeClass('btn-default');
      unlikeButton.addClass('btn-primary');
      unlikeButton.find('.like-number').text(data.counter);
      $('#is-liked').val('false');
      new XWiki.widgets.Notification("The page has been unliked.", 'done');
    }).catch(() => {
      new XWiki.widgets.Notification("Error when trying to unlike the page.", 'error');
    });
  };
  $('.like-button:not(.disabled)').on('click', likeClick);
});
