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("Cette page a été aimée.", 'done');
     }).catch(() => {
       new XWiki.widgets.Notification("Erreur en essayant d&#39;aimer une 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("Cette page n&#39;est plus aimée.", 'done');
    }).catch(() => {
      new XWiki.widgets.Notification("Erreur en essayant de ne plus aimer une page.", 'error');
    });
  };
  $('.like-button').on('click', likeClick);
});
