define('xwiki-like-messages', {
  prefix: 'like.button.title.',
  keys: [
    "unlike",
    "like"
  ]
});
require(['jquery', 'xwiki-meta', 'xwiki-l10n!xwiki-like-messages'], function ($, xm, l10n) {
  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);
       likeButton.attr('title', l10n.get('unlike', 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);
      unlikeButton.attr('title', l10n.get('like', 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').on('click', likeClick);
});
